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 specific requirements. In such cases, it becomes important to restrict what the user can input. In this tutorial, we will be making a program on how to take only an Integer value as an input. If the user inputs any value other than an integer, then the program will ask the user to input another integer value till the user inputs an integer value.

Program for taking only integer input in C++

#include <iostream>
#include <limits>
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
gdjd
Wrong Choice. Enter again 
$*%&%
Wrong Choice. Enter again 
645
The integer is : 645

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’) : To use this function we must first include the <limits> header file. The 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 up to 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 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!

6 responses to “Taking only integer input in C++”

  1. Mac Wilens says:

    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?

  2. ahmed ebrahime says:

    just add #include header before compiling the code
    thanks alot.

  3. david says:

    hello , i had a problem on user input numbers only interms of
    500d452 brings error

  4. Khalid Khurshid Siddiqui says:

    It’s showing error on continue command saying it can only be used in loops

Leave a Reply

Your email address will not be published. Required fields are marked *