#include<iostream>
#include<limits>
int main()
{
int m;
std::cin >> m;
while (std::cin.fail() || m <= 0) {
std::cin.clear();
std::cin >> m;
}
return 0;
}
The above code is supposed to prompt for an input until a positive integer is entered. But even after entering a positive integer it keeps prompting for an input. For example, lets say I have the input as
abc
c4
-3
1
2
.
.
So in principle the moment I enter 1, the execution should be transferred out of the loop. But it keeps prompting for an input and looks like an infinite loop.
After looking around for a while, I modified it as
cin >> m;
while (cin.fail() || m <= 0) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cin >> m;
}
As desired, entering a positive number terminates the loop. I didn't get it. Why the new line character is stuck in the input buffer? Suppose I have this
int a , b;
cin >> a;
cin >> b;
When my input is
1
2
It correctly sets a to 1 and b to 2, instead of setting b to \n.
Why is the behaviour different in the two cases?
bget set to\n?bis an integer.mis being set to\n