Reputation: 27
Any idea why this happen?
void askNQ(int &noq)
{
bool x = true;
while (x)
{
int i;
cout << "How many questions would you like(out of " << noq << ")?" << endl;
cin >> i;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Sorry, that is not valid." << endl;
x = true;
}
else if (i > noq)
{
cout << "Sorry, that is too many." << endl;
x = true;
}
else if (i <= 0)
{
cout << "Sorry, that is too less." << endl;
x= true;
}
}
}
Upvotes: 0
Views: 59
Reputation: 71
You should enter numeric in command line, Since the variable "i" is integer.
Upvotes: 0
Reputation: 170124
cin.ignore();
is in fact a call to cin.ignore(1, char_traits<char>::eof());
.
So you aren't cleaning the buffer out of any leftover newlines.
The following should fix your problem:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
It clears the next newline character, no matter how far it is in the buffer (for all practical purposes).
Upvotes: 1