0

I'm currently doing a simple "how old are you" calculator. But i want to check if the user entered a int or a char. So i made this:

 if (!cin) {

cout << "Error" << endl; 
cin >> year;

}

But if i do this and enter a char it just goes through and doesn't allow a new input.

AnnoyedGuy
  • 111
  • 1
  • 11

1 Answers1

0

Reference: cin for an int inputing a char causes Loop that is supposed to check input to go wild

This is a duplicate but the canonical answer is to do:

std::cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Then do something like:

int year;

 while (!(std::cin >> year)) {
    std::cin.clear(); // clears the error flags
    // this line discards all the input waiting in the stream
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "error" << std::endl;
 }

// do something with year

So if your input looked like:

a
b
c
42

It will print error three times.

Community
  • 1
  • 1