繁体   English   中英

cin.ignore 不工作:即使使用 clear() 也会跳过进一步的输入

[英]cin.ignore not working: further inputs get skipped even with clear()

我正在尝试检查布尔输入,但由于某种原因它一直进入无限循环,或者(如果我将std::cin.ignore()移动到 std::cin.clear std::cin.clear() ) 之后执行的第一件事)要求幻象输入。 我尝试了简单的ignore()ignore(std::numeric_limits<std::streamsize>::max(),'\n')它仍然进入无限循环,似乎跳过了cin输入

代码:

#include <cstdlib>
#include <iostream>
#include <limits>

int main()
{
    std::string testString = "testvar";
    bool value = false;
    do
    {
        std::cin.clear();
        std::cout << "Enter " << testString << " value (true/false)\n";
        std::cin >> std::boolalpha >> value;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        if(!std::cin.fail())
        {
            break;
        }
        std::cout << "Error! Input value is not boolean! Try again.\n";
    }while(true);

    std::cout << value;
}

您的问题是您的操作顺序。

std::cin.clear();
std::cout << "Enter " << testString << " value (true/false)\n";
std::cin >> std::boolalpha >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

您调用clear ,获取输入,然后忽略剩余部分。 问题是如果获取输入部分失败,那么忽略剩余部分也会失败,因为 stream 处于失败的 state 中。您需要做的是获取输入,清除所有错误,然后忽略额外的输入. 那看起来像

std::cout << "Enter " << testString << " value (true/false)\n";
std::cin >> std::boolalpha >> value;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

但这会破坏循环的工作方式。 为了让它工作,你可以使用

do
{
    std::cout << "Enter " << testString << " value (true/false)\n";
    if (std::cin >> std::boolalpha >> value)
        break;
        
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cout << "Error! Input value is not boolean! Try again.\n";
} while(true);

暂无
暂无

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

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