I wish to achieve to limit user on only 0 or 1 when program asking for boolean variable. I\'we tried to do so, but it doesn\'t work. It still keep asking me for typing in.
As chris points out, you want to do if (cin && (ele == 0 || ele == 1)) break;
You cant do that :
if (cin && ele == 0 && ele == 1) break;
because its always false because ele cant be in same time 1 or 0 ... It can be only one of this figures.
if(ele == 0 || ele == 1) break;
The good news is, that operator>>
for bool
by default allows only '0'
or '1'
as valid input. That means you don't need to explicitly check the value after read - if stream state is ok, so is your bool
:
bool ele;
if (!(cin >> ele)) {
// error;
}
The reason you're getting an infinite loop when you enter something like "cvdsavd"
is that you only clear the error flags, but don't get rid of the bad charaters. So your loop keeps trying but never can get a valid input. You need to get rid of the garbage:
bool ele;
while (!(std::cin >> ele)) {
std::cout << "Neveljaven vnos!\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Reference for ignore(). You also need to include <limits>
for numeric_limits
template.
Lp :)