Error Checking / Input Validation In C++ (Integer)

Error Checking / Input Validation In C++ (Integer) will show you how to validate user input and error check for an integer in C++. I hope this deems helpful to you!

Control structures and functions used in this program include a while loop and the .clear() and .ignore() functions.

1. Create A Variable

To begin with, inside of the int main() function, create a variable that will store user input.

int num;

2. Ask User For Number

Then, ask the user to enter a number.

cout << "Enter your favorite number: ";

3. Receive User Input

Next, we need to receive the users input into the num variable. However, in order to input validate we must place the cin >> num; within the text expression of a while loop.

while (!(cin >> num))


Make sure to wrap the cin >> num; between two parentisis () and use the ! symbol. Otherwise the program will accept all other data types except integers. So, watch out!

4. Explain, Clear, and Discard Previous Input

Now, within the while loop, if the user’s input is anything other than an integer, we will need to explain the error, clear the input stream, and discard previous input.

while (!(cin >> num))
    // Explain error
    cout << "ERROR: a number must be entered: ";

    // Clear input stream

    // Discard previous input
    cin.ignore(123, '\n');

It is important to mention here that the .ignore() function takes two arguments–The first being an integer that tells the program to skip the next 123 characters up until new line character ('\n')–the second argument. Remember, if neither the .clear() function nor the .ignore() function are used, then the program will leave user guessing what to do next after entering a number. And that’s not good. So pay attention here.

5. Display Input & Salutation

Finally, after the user’s input is validated, display the number, say good bye, and end the program.

// Display the number the user has entered
cout << "Your favorite number is: " << num << endl;
// Salutation
cout << "Thanks. Bye." << endl;

return 0;

6. That’s it for Error Checking / Input Validation In C++ (Integer)

To view FULL CODE, refer to this GitHub repository and YouTube video here. Otherwise, thank you for taking interest in this post.

  • Jesús Hilario H.

Leave a Reply