Open In App

How to Ask User Input Until Correct Input is Received?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

User input is a common source of errors in C++ programs so it’s important to validate user input to make the program more reliable. In this article, we will discuss how to ask the user for input until valid input is received in our C++ program.

For Example,

Input:
asdf

Output:
Incorrect Input. Please Enter Valid Input.

User Input Validation

The easiest method for prompting the user for valid input is using a loop that iterates till the valid input is entered. We can enclose the cin in that loop and keep taking input till the correct input is recieved.

C++ Program to Validate User Input

The below example asks the user till the numeric value is entered.

C++




// C++ program to prompt the user for positive integer as
// input
  
#include <iostream>
#include <limits>
using namespace std;
  
int main()
{
    int userNumber;
  
    cout << "Enter a positive integer: ";
    while (!(cin >> userNumber) || userNumber <= 0) {
        cin.clear(); // Clear error flags
        cin.ignore(numeric_limits<streamsize>::max(),
                   '\n'); // Ignore bad input
        cout << "Invalid input. Please enter a positive "
                "integer: ";
    }
  
    cout << "You entered a positive integer: " << userNumber
         << endl;
  
    return 0;
}


Output

Enter a positive integer: -1
Invalid input. Please enter a positive integer: 

Explanation: The above program starts by giving a prompt to the user for entering a positive integer. Then it checks using a while loop whether the given input is valid or not. If the input is invalid (either not an integer or not positive), the loop clears the error state of std::cin, ignores the bad input, and prompts the user again. Once a valid input is received, the loop exits and the program prints the entered positive integer.

Note: In order to meet unique needs, we can modify the input validation logic.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads