[英]End of File and Status of a Input Stream C++
我目前正在尝试从C ++中只有一行的文本文件读取输入; 我能够使用std :: getline(file,string)从文件成功地将一行文本提取到字符串中。 提取行后,不再有文本。 当我尝试检查流的状态时,调用file.good()并到达文件的已知“结尾”时,它将永远不会返回false。 为什么是这样? 参见下面的代码:
#include<fstream>
#include<cstring>
using namespace std;
ifstream file;
string test;
file.open("HW6.txt");//HW6.text is one line text file
getline(file,test);//extracts the line of text; file should be blank now
cout<<file.good(); //this returns true
getline(file,test); //attempt to extract text from blank file
cout<<file.good(); //this returns true still
以表格形式非常不错地总结了istream::good()
在http://en.cppreference.com/w/cpp/io/basic_ios/good返回true
和false
时间。
仅当以下标志均不为真时, istream::good()
返回真:
eofbit
failbit
badbit
对于您来说,流仍然处于良好状态,因为您在成功读取该行之后没有尝试读取其他任何内容。
这是来自cplusplus.com的示例。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
string line;
ifstream f(argv[1]);
if (f.is_open()) {
while ( getline (f,line) ) {
// if (line.size())
cout << line << endl;
}
f.close();
} else cerr << "Unable to open file " << argv[1] << endl;
return 0;
}
如果不需要空白行,则可以取消注释if
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.