I have this code:
double input2;
cout<<"please enter one number:"<<endl;
cin>>input2;
How can I judge if the user input only about digits, like '3', '4', or '4.241'. Sometimes when users enter a character like 'n', '3.q', my program will crash.
I have this code:
double input2;
cout<<"please enter one number:"<<endl;
cin>>input2;
How can I judge if the user input only about digits, like '3', '4', or '4.241'. Sometimes when users enter a character like 'n', '3.q', my program will crash.
You can use stringstream to convert a string safely to number:
string input;
int mynumber;
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
cout <<"number is valid"<<endl;
else
cout<<"invalid number";
cin::<<
operator returns NULL
if operation went bad. Causes may be many but if interpretation fails then the failbit
is set. You can check it with rdstate()
:
int main()
{
double input2;
cout<<"please enter one number:" << endl;
cin >> input2;
if (cin.rdstate() & ifstream::failbit)
cout << "input badly formatted" << endl;
return 0;
}
It won't crash because of that. If the cin >> input2 operation fails because of invalid input, cin is put in an invalid state, but it won't crash.
You need to verify that the input was auccessful
if (std::cin >> input2) {
...
}
.. and if it wasn't deal with the erronous input, e.g.:
std::cin.clear();
std::cin.ignore();