codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ input validation

C++ input validation

Reject bad input.

If cin fails, clear the error and ignore the rest of the line before asking again.

Example code

#include <iostream>
#include <limits>
using namespace std;
int main() {
  int n;
  while (!(cin >> n) || n < 1 || n > 10) {
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Enter 1 to 10: ";
  }
  cout << "OK " << n << endl;
  return 0;
}

Run this code in the online editor

← C++ exceptionsC++ STL and vectors →