我写了这个简单的代码:
#include <iostream>
using namespace std;
int main()
{
double s;
cin >> s;
if (cin.fail())
cout<<"Error";
return 0;
}
当我输入 12.03
时,cin.fail()
返回 false
,这很好。
当我输入 sd234
时,cin.fail()
返回 true
,这也很好。
但是,如果我输入 234.abcd
,或者任何后跟一个字符的数字,cin.fail()
返回 true
尽管我没有通过 cin
向 double
变量输入数字。
我错过了什么?
最佳答案
std::istream::operator>>()读取适合当前类型的字符(例如,数字和 . 用于 double
)。以下字符留在输入缓冲区中,供另一个提取运算符使用。如果读取到的字符能满足当前类型,则不报错。
关于c++ - 为什么在输入数字后跟字符时 cin.fail() 不返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13546911/