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

Viewed 32740

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?

6 Answers

I would use:

double x;

while (!(std::cin >> x)) {
  std::cin.clear();
  std::cin.ignore(2147483647, '\n');
  std::cout << "Error.\n";
}

or

double x;

while ((std::cout << "> ") && !(std::cin >> x)) {
  std::cin.clear();
  std::cin.ignore(2147483647, '\n');
  std::cout << "Error.\n";
}
Related