当代码完成时,为什么我会获得额外的迭代(额外的行打印)? EOF中是否需要额外的换行符?我宁愿不必添加额外/特殊字符来标记EOF。带有额外最终迭代的文件回显循环
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream infile("dictionary.txt"); // one word per line
string text;
while(infile){
infile >> text;
cout << text << endl;
}
infile.close();
return 0;
}
你能否证实“dictionary.txt”没有一个新的行末?因为你的代码似乎是直接读入,写出。 – Nasir 2009-10-06 20:38:17
@ nr81:这是读取文件的标准反模式。因为在读取之后没有测试eof(使用操作符>>),那么最后一行将被打印两次。请参阅下面的回复,了解正确的读取文件模式。 – 2009-10-06 20:52:46