是否可以使用getline()
讀取有效文件而不設置failbit
?我想使用failbit
,以便在輸入文件不可讀時生成異常。使用getline()而不設置failbit
以下代碼始終輸出basic_ios::clear
作爲最後一行 - 即使指定了有效的輸入。
test.cc:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream inf;
string line;
inf.exceptions(ifstream::failbit);
try {
inf.open(argv[1]);
while(getline(inf,line))
cout << line << endl;
inf.close();
} catch(ifstream::failure e) {
cout << e.what() << endl;
}
}
input.txt中:
the first line
the second line
the last line
結果:
$ ./a.out input.txt
the first line
the second line
the last line
basic_ios::clear
使用函數getline時提出的failbit():
不管怎麼說,上面的代碼應該寫成? – selalerer
如果文件不存在。例如'./a.out nosuchfile.txt' – Jeremiah
爲此,您可以在打開文件後檢查is_open()。 – selalerer