c++ cin only boolean(0,1)

后端 未结 3 2010
迷失自我
迷失自我 2021-01-15 19:21

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.

相关标签:
3条回答
  • 2021-01-15 19:29

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

    0 讨论(0)
  • 2021-01-15 19:47

    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;
    
    0 讨论(0)
  • 2021-01-15 19:48

    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 :)

    0 讨论(0)
提交回复
热议问题