Home >Backend Development >C++ >How Can I Validate Integer Input in C ?
Checking Integer Input Stream in C
In C , verifying user input to ensure it's an integer can be challenging. This article demonstrates two methods to achieve this validation.
Method 1: Checking Input Failure
To check if input is an integer, use the following snippet:
int x; cin >> x; if (cin.fail()) { // Not an integer }
If the entered value cannot be converted to an integer, cin.fail() returns true, indicating a non-integer input.
Method 2: Continuously Prompting for Integer Input
To repeatedly prompt for an integer until a valid input is entered, use this code:
int x; std::cin >> x; while (std::cin.fail()) { std::cout << "Error" << std::endl; std::cin.clear(); std::cin.ignore(256, '\n'); std::cin >> x; }
The while loop continues until a valid integer is entered, clearing and ignoring previous invalid inputs.
Example
Consider the following code:
int firstvariable; int secondvariable; cout << "Please enter two integers and then press Enter:" << endl; cin >> firstvariable; cin >> secondvariable;
Using either of the methods described above, you can check if firstvariable and secondvariable are integers and handle non-integer inputs appropriately.
The above is the detailed content of How Can I Validate Integer Input in C ?. For more information, please follow other related articles on the PHP Chinese website!