今天在调试一个初级的文件流程序时出现了如下的情况。源程序如下:
#include <fstream>
#include <iostream>
void main(){
using namespace std;
ifstream in("a.in");
ofstream out("a.out");
for (string str;getline(in,str);){
out<<str<<endl;
}
}
编译时报错:
--------------------Configuration: new2 - Win32 Debug--------------------
Compiling...
n1.cpp
E:/VC6.0/MSDev98/MyProjects/new2/n1.cpp(8) : error C2065: 'getline' : undeclared identifier
E:/VC6.0/MSDev98/MyProjects/new2/n1.cpp(9) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable
conversion)
执行 cl.exe 时出错.
n1.obj - 1 error(s), 0 warning(s)
我在网上查询关于这个问题的解决方法时,没有找到解决方法,因为许多人都注意到了环境、头文件的对错问题。我无意间看到了一个人写的错误的程序中有string这个头文件,我就试着加入这个头文件,结果问题解决了。
修改后的代码如下:
#include <fstream>
#include <iostream>
#include <string>
void main(){
using namespace std;
ifstream in("a.in");
ofstream out("a.out");
for (string str;getline(in,str);){
out<<str<<endl;
}
}
一切OK。
但是问题在于,为什么其他人编写这个程序时就没有写入string头文件,但是也成功运行了呢?这就不得而知了,继续关注……