0

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.

René Höhle
  • 26,716
  • 22
  • 73
  • 82
user1804033
  • 53
  • 1
  • 6
  • Have a look at this Question it is similar to yours http://stackoverflow.com/questions/545907/what-is-the-best-way-to-do-input-validation-in-c-with-cin – zero298 Nov 24 '12 at 23:33

4 Answers4

2

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";
Jagdeep Sidhu
  • 351
  • 1
  • 7
1

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;
}
Jack
  • 131,802
  • 30
  • 241
  • 343
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.

user1610015
  • 6,561
  • 2
  • 15
  • 18
0

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();
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380