std::basic_ios<CharT,Traits>::good
来自 cppreference.com
bool good() const; |
||
如果流上最近的 I/O 操作成功完成,则返回 true。具体来说,返回 rdstate() == 0 的结果。
有关设置流状态位的条件列表,请参阅 ios_base::iostate。
内容 |
[编辑] 参数
(无)
[编辑] 返回值
如果流错误标志均为假,则返回 true,否则返回 false。
[编辑] 示例
运行此代码
#include <cstdlib> #include <fstream> #include <iostream> int main() { const char* fname = "/tmp/test.txt"; std::ofstream ofile{fname}; ofile << "10 " << "11 " << "12 " << "non-int"; ofile.close(); std::ifstream file{fname}; if (!file.good()) { std::cout << "#1. Opening file test.txt failed - " "one of the error flags is true\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for (int n; file >> n;) std::cout << n << ' '; std::cout << '\n'; if (file.bad()) { std::cout << "#2. I/O error while reading - badbit is true\n"; return EXIT_FAILURE; } else if (file.eof()) std::cout << "#3. End of file reached successfully - eofbit is true\n" "This is fine even though file.good() is false\n"; else if (file.fail()) std::cout << "#4. Non-integer data encountered - failbit is true\n"; }
可能的输出
10 11 12 #4. Non-integer data encountered - failbit is true
[编辑] 另请参阅
下表显示了 basic_ios 访问器(good()、fail() 等)对于所有可能的 ios_base::iostate 标志组合的值
ios_base::iostate 标志 | basic_ios 访问器 | |||||||
eofbit
|
failbit
|
badbit
|
good() | fail() | bad() | eof() | operator bool | operator! |
false | false | false | true | false | false | false | true | false |
false | false | true | false | true | true | false | false | true |
false | true | false | false | true | false | false | false | true |
false | true | true | false | true | true | false | false | true |
true | false | false | false | false | false | true | true | false |
true | false | true | false | true | true | true | false | true |
true | true | false | false | true | false | true | false | true |
true | true | true | false | true | true | true | false | true |