简体   繁体   中英

Validating input in C++

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, eg:

std::cin.clear();
std::cin.ignore();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM