简体   繁体   English

C ++使用cin.fail()和cin.clear()-我有一个无限循环,不知道为什么

[英]C++ Using cin.fail(), cin.clear() — I have an infinite loop and don't know why

Can you not use cin and then cin.fail() in the same line like this? 您不能在同一行中使用cin然后使用cin.fail()吗? Is there a cleaner or more standard way to do this type of error checking upon input?--perhaps not using a do-while. 有没有更清洁或更标准的方法可以在输入时执行这种类型的错误检查?-也许不使用do-while。

do {
     cin.clear();
     cout << "\nPlease enter the size of the array (1-10): ";
} while (cin >> array_size && array_size <= 1 || array_size >= 10 || cin.fail());

This one works: 这个作品:

do {
    cout << "Please input #: ";
    if (cin.fail()){
        cin.clear();
        cin.ignore(80, '\n');
    }
    cin >> kids_total;
} while (cin.fail() || kids_total <= 0);
cin >> array_size && array_size <= 1 || array_size >= 10 || cin.fail()

Say you've got a letter next in cin , cin >> array_size evaluates false so the && short-circuit evalusation skips over array_size <= 1 to test: 假设您接下来在cin有一封信, cin >> array_size评估结果为false因此&&短路评估跳过array_size <= 1进行测试:

  • array_size >= 10 : might be uninitialised memory read ==> undefined behaviour, otherwise presumably false array_size >= 10 :可能是未初始化的内存,读取==>未定义的行为,否则可能为false
  • cin.fail() - definitely true cin.fail() -绝对true

...unless there's undefined behaviour - and maybe even then - the loop will continue without having removed the letter from cin , only to fail again immediately. ...除非存在未定义的行为-甚至即使这样-循环仍将继续而不会删除cin的字母,只会立即再次失败。

Check cin.ignore for a way to remove input that's failed parsing, or use std::getline(std::cin, my_string) , std::istringstream iss(my_string); if (iss >> array_size 检查cin.ignore以找到一种方法来删除解析失败的输入,或者使用std::getline(std::cin, my_string)std::istringstream iss(my_string); if (iss >> array_size std::istringstream iss(my_string); if (iss >> array_size etc. for a way to guarantee the entire line's thrown away on bad input.... std::istringstream iss(my_string); if (iss >> array_size等,以确保在错误的输入中将整个行丢弃。...


For comparison, this is pretty robust and IMHO intuitive if verbose. 为了比较,这很健壮,恕我直言,如果冗长。 If doing it more than once, just create a function.... 如果多次执行此操作,只需创建一个函数即可。...

while (true)
{
    std::cout << "Please input #: ";
    if (std::cin >> kids_total)
    {
        if (kids_total > 0)
            break;
        std::cout << "Value must be > 0, please try again.\n";
    }
    else if (std::cin.eof())
    {
        // rare for keyboard input - e.g. ^D on UNIX/Linux, ^Z Windows
        // can happen with pipes/redirects - e.g. echo 10 20 | ./my_app
        std::cerr << "expected value for kids_total but encountered end of input\n";
        exit(EXIT_FAILURE);
    }
    else
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM