Taking only integer input in C++
In this tutorial, we will learn about how to take only integer input in C++.
A lot of times we encounter the problem that the data input by the user does not match the specifics required for the input. In such cases, it becomes important to restrict what the user can input. In this tutorial, I will be making a program on how to take only an integer as an input. If the user inputs any value other than an integer, the program will ask the user to input another integer value.
Program for taking only integer input in C++
#include <iostream> using namespace std; int main() { int i; cout << "enter an integer" << endl; while (true) { cin >> i; if (!cin) { cout << "Wrong Choice. Enter again " << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); continue; } else break; } cout << "The integer is : " << i; return 0; }
Output :
enter an integer abc Wrong Choice. Enter again !#$ Wrong Choice. Enter again 123 The integer is : 123
Explanation :
cin.clear(): It clears the error flag on cin (so that future I/O operations will work correctly)
cin.ignore(numeric_limits<streamsize>::max(), ‘\n’) : ignore function is used to ignore or skip (or discard/throw away) characters in the input stream. It ignores the characters upto a specified number or until a delimiter is read. When the number of characters is unknown, we use numeric_limits<streamsize>::max() to ignore upto the maximum length of any string passed. The delimiter I passed here is ‘\n’ (the second parameter).
This program keeps on asking for a value until an integer value is given as an input by the user. It displays the output ‘Wrong Choice. Enter again’ to take another input. When you finally input an integer value, the loop finishes and the value of the input integer is displayed.
Hope this was helpful. Enjoy Coding!
You may also read:
Thank you. However, if you key in 1A , or 10X; then CIN loads the numeric portion into the variable.
Is there any simple (less than 20 lines) to reject the input when it has any non-numeric characters?
just add #include header before compiling the code
thanks alot.
if we get input 12s then it takes 12 which is not correct please give us feedback on how can we tackle this problem
Yeah, I want to know how to solve this too.
hello , i had a problem on user input numbers only interms of
500d452 brings error
It’s showing error on continue command saying it can only be used in loops