I wrote this simple code:
#include <iostream>
using namespace std;
int main()
{
double s;
cin >> s;
if (cin.fail())
cout<<"Error";
return 0;
}
When I enter 12.03, cin.fail() returns false, and that’s good.
And when I enter sd234, cin.fail() returns true, which is also good.
But if I enter 234.abcd, for example, or any number followed by a characters, cin.fail() returns true although I didn’t enter a numerical to the double variable through the cin.
What am I missing?
std::istream::operator>>() reads characters as long as it fits to the current type (e.g. digits and . for
double). Following characters are left in the input buffer for another extraction operator. If the characters read can satisfy the current type, no error is signaled.