首页 > 解决方案 > 检查输入是否为整数,并且输入超过 1 个字符会导致在控制台中打印多条语句,而不是只打印一次

问题描述

    {
        valid = true; //Assume the cin will be an integer.
        cin >> menuValue;

        if (cin.fail()) //cin.fail() checks to see if the value in the cin
                        //stream is the correct type, if not it returns true,
                        //false otherwise.
        {
            cin.clear();  //This corrects the stream.
            cin.ignore(); //This skips the left over stream data.
            cout << "Please enter an Integer from 1-6 only." << endl;
            valid = false; //The cin was not an integer so try again.
        }
    }

我试图做一个错误检查点,用户在哪里输入不是整数的东西,它会要求他们控制输入数字,唯一的问题是如果我要输入诸如 jiasdhais 之类的东西,它会打印与输入长度相同的消息多次。有什么办法吗?

标签: c++

解决方案


尝试这个:

{
    int input;
    if( !( std::cin >> input) ){
        //in case of fail do stuff
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } else {
        //then check for 1-6
        //your code ...
    }
}

如果输入不是整数,它将被丢弃。更具体地说,如果您的体系结构将 int 保存为 4 字节,则输入应在 -2,147,483,648 到 2,147,483,647 的范围内,否则将被丢弃。


推荐阅读