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

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

问题描述

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

解决方案

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

  //如果输入执行循环失败(例如,没有字符被读取)
while(std :: cout<<输入数字&&!(std :: cin>> num)){
std :: cin.clear(); // clear bad input flag
std :: cin.ignore(std :: numeric_limits< std :: streamsize> :: max(),'\\\
'); // discard input
std :: cout<< 输入无效,请重新输入。
}

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



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

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.

解决方案

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

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

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天全站免登陆