iostream与iostream.h; string与string.h

今天写了一个简单的C++标准输入输出的小程序

#include <iostream>

int main()
{
    int v1,v2;
    cout << "Enter two numbers:" << endl;
    cin >> v1 >> v2;
    cout <<"the sum of " << v1 <<" and " << v2
        << " is " << v1 + v2 << endl;
    return 0;
}

编译无法通过,错误为cout,endl,cin没有定义

把#include<iostream>改为#include<iostream.h>编译通过

查询了一下资料发现,头文件中加.h是过时的规则,官方不提倡使用。C++标准是不加.h的

iostream的各组成以STL形式声明的,iostream.h的各组成声明成全局变量

头文件使用<iostream>表示使用命名空间,所以文件头要加一句 using namespace std;这是遵循C++标准的

这里看一下iostream.h的源代码:

#ifndef _BACKWARD_IOSTREAM_H 
#define _BACKWARD_IOSTREAM_H 1 
#include "backward_warning.h" 
#include <iostream>  // 看到这里应该更加清晰了吧!  
using std::iostream; // 看到这些using声明应该知道为什么可以在使用iostream.h的时候不用using namespace std了吧?  
using std::ostream;  
using std::istream;  
using std::ios;  
using std::streambuf;  
using std::cout;  
using std::cin;  
using std::cerr;  
using std::clog; 
#ifdef _GLIBCXX_USE_WCHAR_T  
using std::wcout;  
using std::wcin;  
using std::wcerr;  
using std::wclog; 
#endif  
using std::ws;  
using std::endl;  
using std::ends;  
using std::flush; 
#endif  
// Local Variables:  
// mode:C++  
// End: 

所以文件改为遵循C++标准:

#include <iostream>
using namespace std;

int main()
{
    int v1,v2;
    std::cout << "Enter two numbers:" << std::endl;
    std::cin >> v1 >> v2;
    std::cout <<"the sum of " << v1 <<" and " << v2
        << " is " << v1 + v2 << std::endl;
    return 0;
}

 

同样区别<string.h>与<string>

string.h是C头文件,处理char*字符串

string是c++标准头文件,处理string类,要使用命名空间,using namespace std;

<cstring>是对应C的C++头文件

如:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int v1,v2;
    string str1,str2;
    std::cout << "Enter two numbers:" << std::endl;
    std::cin >> v1 >> v2;
    std::cout <<"the sum of " << v1 <<" and " << v2
        << " is " << v1 + v2 << std::endl;
    std::cout << "Enter two string: " << std::endl;
    std::cin >> str1 >> str2;
    std::cout << "the string is " << str1 << " and " << str2
        << " the sum is " << str1+" "+str2 << endl;
    return 0;
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值