下载贤集网APP入驻自媒体
C++ Primer中说道: 当failbit和badbit被置位时, 那么fail()返回true. 还有: 我们将流作为条件使用的代码就等价于!fail()标准ISO中也这样说 http://www.cplusplus.com/reference/ios/ios/fail/
所以我的理解就是: if(cin >> x) 就等价于 if(!(cin >> x).fail())
这样正确吗?
但是我测试之后有点小问题:
我的代码如下:
#include <iostream>
using namespace std;
void check_cin_state(istream & is)
{
if (cin.eof())
cout << "cin eof()" << endl;
else
cout << "cin not eof()" << endl;
if (cin.fail())
cout << "cin fail()" << endl;
else
cout << "cin not fail()" << endl;
if (cin.bad())
cout << "cin bad()" << endl;
else
cout << "cin not bad()" << endl;
if (cin.good())
cout << "cin good()" << endl;
else
cout << "cin not good()" << endl;
cout << endl;
}
int main()
{
int x;
if (cin >> x)
check_cin_state(cin);
check_cin_state(cin);
return 0;
}当我在windows电脑上输入Ctrl + Z 的时候,
输出如下:
cin eof()
cin fail()
cin not bad()
cin not good()