C++ 如何处理错误的数据类型输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10349857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:55:35  来源:igfitidea点击:

How to handle wrong data type input

c++inputtypeserror-handling

提问by Zik

In C++, how do you handle wrong inputs? Like, if the program asks for an integer, when you type a character it should be able to do something and then loop to repeat the input but the loop goes infinite when you input a character when an integer is need and vice versa.

在 C++ 中,你如何处理错误的输入?就像,如果程序要求输入一个整数,当你输入一个字符时,它应该能够做一些事情然后循环重复输入,但是当你输入一个字符时循环无限,反之亦然。

回答by chris

The reason the program goes into an infinite loop is because std::cin's bad input flag is set due to the input failing. The thing to do is to clear that flag and discard the bad input from the input buffer.

程序进入无限循环的原因是因为std::cin输入失败而设置了错误的输入标志。要做的是清除该标志并丢弃来自输入缓冲区的错误输入。

//executes loop if the input fails (e.g., no characters were read)
while (std::cout << "Enter a number" && !(std::cin >> num)) {
    std::cin.clear(); //clear bad input flag
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
    std::cout << "Invalid input; please re-enter.\n";
}

See the C++ FAQfor this, and other examples, including adding a minimum and/or maximum into the condition.

请参阅C++ FAQ和其他示例,包括在条件中添加最小值和/或最大值。

Another way would be to get the input as a string and convert it to an integer with std::stoior some other method that allows checking the conversion.

另一种方法是将输入作为字符串获取并使用std::stoi允许检查转换的其他方法将其转换为整数。

回答by AWolfAtTheDoor

The top voted answer covers the solution really well.

投票最高的答案很好地涵盖了解决方案。

In addition to that answer, this may help visualize what's going on a little better:

除了那个答案,这可能有助于更好地形象化正在发生的事情:

int main()

    int input = 1;//set to 1 for illustrative purposes
    bool cinState = false;
    string test = "##代码##";
    while(input != -1){//enter -1 to exit
        cout << "Please input (a) character(s): ";//input a character here as a test
        cin >> input; //attempting to input a character to an int variable will cause cin to fail
        cout << "input: " << input << endl;//input has changed from 1 to 0
        cinState = cin;//cin is in bad state, returns false
        cout << "cinState: " << cinState << endl;
        cin.clear();//bad state flag cleared
        cinState = cin;//cin now returns true and will input to a variable
        cout << "cinState: " << cinState << endl;
        cout << "Please enter character(s): ";
        cin >> test;//remaining text in buffer is dumped here. cin will not pause if there is any text left in the buffer.
        cout << "test: " << test << endl;
    }
    return 0;    
}

Dumping the text in the buffer to a variable isn't particularly useful, however it helps visualize why cin.ignore()is necessary.

将缓冲区中的文本转储到变量并不是特别有用,但它有助于形象化为什么cin.ignore()需要这样做。

I noted the change to the input variable as well because if you're using an input variable in your condition for a whileloop, or a switch statement it may go into deadlock, or it may fulfill a condition you weren't expecting, which can be more confusing to debug.

我也注意到了对输入变量的更改,因为如果您在while循环或 switch 语句的条件中使用输入变量,它可能会陷入死锁,或者它可能会满足您不期望的条件,这可以调试起来更混乱。

回答by AWolfAtTheDoor

Test the input to see whether or not it is what your program expects. If it is not, alert the user that the input they provided is unacceptable.

测试输入以查看它是否是您的程序所期望的。如果不是,请提醒用户他们提供的输入是不可接受的。

回答by vikky

You can check it through the ASCII value if the ascii value s between 65 t0 90 or 97 to 122 the it would be character.

如果 ascii 值介于 65 t0 90 或 97 到 122 之间,则可以通过 ASCII 值检查它是字符。