C++ 最后一个空行和ifstream::operator>&燃气轮机;(C+;+;)
我对以下代码中的ifstream::operator>>行为有疑问:C++ 最后一个空行和ifstream::operator>&燃气轮机;(C+;+;),c++,operator-keyword,ifstream,C++,Operator Keyword,Ifstream,我对以下代码中的ifstream::operator>>行为有疑问: #include <iostream> #include <string> #include <fstream> using namespace std; int main () { ifstream inFile("test.txt"); string buffer; while (!inFile.eof()) { inFile >>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main () {
ifstream inFile("test.txt");
string buffer;
while (!inFile.eof()) {
inFile >> buffer;
cout << buffer << endl;
}
return 0;
}
但是,如果test.txt是这样写的:
One two
Three four
Five six
(empty line)
cout
将显示两个“六”字符串。
这是与Windows或类似的\r\n相关的问题吗?
我使用微软VC++2010
提前谢谢 在阅读之前,它还不是EOF。但由于EOF reach,上次读取操作失败 您可以使用
fail
检查上次读取是否失败:
int main () {
ifstream inFile("test.txt");
string buffer;
while (!inFile.eof()) {
inFile >> buffer;
/**EDIT**/
if(!inFile.fail()){
cout << buffer << endl;
}else{
cout << endl;
}
}
return 0;
}
int main(){
ifstream-infle(“test.txt”);
字符串缓冲区;
而(!infle.eof()){
填充>>缓冲区;
/**编辑**/
如果(!infle.fail()){
cout使用stream.eof()
进行循环控制通常是错误的:您总是要在阅读后检查结果:
while (inFile >> buffer) {
...
}
格式化读取将以跳过前导空格开始。之后,字符串提取器将读取非空格字符。如果没有此类字符,提取将失败,流将转换为false
整个问题的可能重复归结为:while(!infle.eof())
…while(infle>>buffer)…似乎工作正常。如中所述,谢谢Zac。当我尝试您的代码时,infle.gcount()总是返回0。我猜运算符您不想使用执行此类操作,而(!istream::eof())
。这会使您的代码比其他情况下复杂得多。我的错误您是对的。我已编辑了答案。为此,如果(!infle.fail())您可以使用。
while (inFile >> buffer) {
...
}