此代码始终打印文件的最后一行。我期望它从文件中一次打印出所有文本。任何想法为什么它不起作用?使用getline()从文件读取时出错无法使用C++
string filename;
cout << "File to read: ";
cin >> filename;
ifstream afile;
afile.open(filename.c_str());
string line;
while(!afile.eof()) {
getline(afile, line);
cout << line;
}
afile.close();
尝试这种方式做同样的事情:
for (string line; getline(afile, line);) {
cout << line;
}
也许这是我的终端的问题吗?这工作...
for (string line; getline(afile, line);) {
cout << line << endl;
}
http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – chris
我没有在for循环中检查eof,为什么它会这样做一样? – David
出了什么问题?怎么了? –