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:

Leave a Reply

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