Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I validate user input as a double in C++?

How would I check if the input is really a double?

double x;

while (1) {
    cout << '>';
    if (cin >> x) {
        // valid number
        break;
    } else {
        // not a valid number
        cout << "Invalid Input! Please input a numerical value." << endl;
    }
}
//do other stuff...

The above code infinitely outputs the Invalid Input! statement, so its not prompting for another input. I want to prompt for the input, check if it is legitimate... if its a double, go on... if it is NOT a double, prompt again.

Any ideas?

like image 375
Hristo Avatar asked Jul 18 '10 01:07

Hristo


1 Answers

Try this:

while (1) {
  if (cin >> x) {
      // valid number
      break;
  } else {
      // not a valid number
      cout << "Invalid Input! Please input a numerical value." << endl;
      cin.clear();
      while (cin.get() != '\n') ; // empty loop
  }
}

This basically clears the error state, then reads and discards everything that was entered on the previous line.

like image 143
casablanca Avatar answered Sep 28 '22 08:09

casablanca