[英]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.