#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream infile("abc.txt");
if(!infile) {}
ofstream outfile("out.txt");
string str;
for(int i=0; i< 1000; i++)
{
getline(infile,str); //这里的问题是如果infile到头了,依旧对str赋值吗?
cout<<str<<endl;
outfile<<str<<endl; //那么这里呢?仍然输出到outfile?是什么形式呢?
}
return 0;
}
答:如果infile到头了,那么getline(infile,str)将会把str赋值为最后一行,在这个例子里将不断重复。比如说文件abc.txt内容为:a /n b/n c/n the end of the file EOF那么str将一直被赋值为the end of the file。但是如果最后the end of the file /n EOF,str将被赋值为空字符,记住getline是省略掉最后的/n的
std::getline(ifstream& , string &)的返回类型是ifstream&,如果infile碰到EOF之后,couture<<getline(infile, str);结果将是00000000.可以在if语句while语句中利用这点做判断。
另一个判断方式就是infile.eof()。在C++primer 4thed里头说“流的状态由bad,fail,eof和good操作揭示。如果bad,fail或者eof中的任意一个为true,则检查流本身将显示该流处于错误状态。……clear操作将条件重新设为有效状态”,这里看来,VS2008编译器已经做了优化,对于eof状态为true的流也可以重复读取最后一行(就是EOF所在的行)。当然这件事情是好是坏也不好说。