c++ cin only boolean(0,1)

2022-01-19 00:00:00 boolean c++

当程序要求布尔变量时,我希望将用户限制在 0 或 1 上.我试图这样做,但它不起作用.它仍然一直要求我输入.

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.

bool ele;
do{ 
    cout << "Elektro:	"; 
    cin >> ele; 
    if (cin && ele == 0 && ele == 1) break;
    cin.clear();
    cout << "Neveljaven vnos!" << endl;
}while(true);

推荐答案

正如 chris 指出的,你想做 if (cin && (ele == 0 || ele == 1)) break;

As chris points out, you want to do if (cin && (ele == 0 || ele == 1)) break;

相关文章