如何处理错误的数据类型输入 [英] How to handle wrong data type input

查看:155
本文介绍了如何处理错误的数据类型输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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.

//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";
}

请参阅 C ++常见问题解答及其他示例,包括在条件中添加最小值和/或最大值。

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

另一种方法是将输入作为一个字符串,并将其转换为一个整数,其中包含 std :: stoi 或允许的其他方法检查转换。

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

这篇关于如何处理错误的数据类型输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆