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

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.

Leave a Comment