Sidharth Raja
Sidharth Raja

Reputation: 307

Check whether input taken by a int datatype is valid

I have an integer variable named i.

When reading from cin:

cin >> i;

How can I confirm that the user input is a valid integer, and not just any character?

Upvotes: 0

Views: 353

Answers (1)

Bart van Ingen Schenau
Bart van Ingen Schenau

Reputation: 15768

You can check if the last (set of) input succeeded with

if (cin) { /* still good */ }

or

if (cin.good()) { /* still good */ }

You can also get the input and check the success in one go:

if (cin >> i) { /* still good */ }

All of these methods have one drawback, and that is that the offending input will not be removed from cin and there is no way to tell mow much there is.

A more robust way of getting user input and validating it is to first read a line of input into a string and then extract the information from that string. For example:

string line;
int i;
if (getline(cin, line))
{
  stringstream ss(line);
  if (ss >> i)
  {
    /* we have got our int */
  }
  else
  {
    /* That was not an integer entered by the user */
  }
}
else
{
  /* The user did not enter anything */
}

Upvotes: 1

Related Questions