如何清洁cin? [英] How do I sanitise cin?
问题描述
说我有一个接受整数的程序。
Say I have a program that takes in integers. How do I stop the program from falling apart if the user enters an out of range number, or a letter or something?
推荐答案
如果用户输入超出范围的数字, cin
的基本类别是 std :: basic_istream
。在输入流不能从流中提取所请求的数据的情况下,输入流指示可恢复的错误。为了检查该错误位,请 std :: basic_istream :: fail()
方法 - 如果失败或 false,则返回
如果一切都好的。重要的是要记住,如果有错误,数据留在流中,当然,错误位也必须使用 true
std :: basic_istream :: clear()
。此外,程序员必须忽略不正确的数据,否则尝试读取其他数据将再次失败。为此, std :: basic_istream :: ignore()
方法。对于值的有效范围,必须手动检查。好的,足够的理论,这里是一个简单的例子:
The cin
's base class is std::basic_istream
. The input stream indicates a recoverable error in case it cannot extract the requested data from the stream. In order to check for that error bit, std::basic_istream::fail()
method must be used — it returns true
if there was a failure or false
if everything is alright. It is important to remember that if there is an error, the data is left in the stream and, of course, the error bit(s) must also be cleared using std::basic_istream::clear()
. Also, a programmer must ignore incorrect data, or otherwise an attempt to read something else will fail again. For that purpose, std::basic_istream::ignore()
method can be used. As for the valid range of values, it must be checked manually. Okay, enough theory, here is a simple example:
#include <limits>
#include <iostream>
int main()
{
int n = 0;
for (;;) {
std::cout << "Please enter a number from 1 to 10: " << std::flush;
std::cin >> n;
if (std::cin.fail()) {
std::cerr << "Sorry, I cannot read that. Please try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if (n < 1 || n > 10) {
std::cerr << "Sorry, the number is out of range." << std::endl;
continue;
}
std::cout << "You have entered " << n << ". Thank you!" << std::endl;
break;
}
}
希望它有帮助。祝你好运!
Hope it helps. Good Luck!
这篇关于如何清洁cin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!