今天写了一个简单的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;
}