I am trying to read an integer from terminal. Here's my code:
int readNumber()
{
int x;
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore();
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
return x;
}
Whenever I run this code I get:
Type in the number for the newsgroup that shall be deleted:
joöä
Bad entry. Enter a NUMBER: Bad entry. Enter a NUMBER: Bad entry. Enter a NUMBER: Bad entry. Enter a NUMBER: Bad entry. Enter a NUMBER: Bad entry. Enter a NUMBER: 8
Why does it write "bad entry" multiple times?
If I remove std::cin.clear();
or std::cin.ignore();
, the program just keeps writing
Enter a NUMBER: Bad entry.
Can anyone explain why it does that?