首页 > 解决方案 > cin.ignore 不起作用:即使使用 clear() 也会跳过进一步的输入

问题描述

我正在尝试进行检查的布尔输入,但由于某种原因,它不断进入无限循环,或者(如果我移动std::cin.ignore()到之后执行的第一件事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;
}

标签: c++

解决方案


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

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');

你打电话claer,得到输入,然后忽略剩菜。问题是如果获取输入部分失败,那么忽略剩余部分也会失败,因为流处于失败状态。您需要做的是获取输入,清除任何错误,然后忽略额外的输入。那看起来像

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

推荐阅读