c++ - 检查输入是否为整数,并且输入超过 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 之类的东西,它会打印与输入长度相同的消息多次。有什么办法吗?
解决方案
尝试这个:
{
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 的范围内,否则将被丢弃。
推荐阅读
- python - 模板在 Django 中不存在
- javascript - 如何在文件上传器中检索文件的内容
- swift - 如何将包含自定义结构数组的自定义类型对象保存到领域(快速)?
- reactjs - 在服务器端(nextjs/apiRoutes)使用firebase/firestore获取多个数据=问题=>在数据准备好之前输出
- ajax - WP_Query 在插件 WP_AJAX 中不起作用
- csv - 使用批处理文件将字段标题插入 CSV
- python - 如何处理不平衡的类?
- javascript - webpack 排除属性与 webpack-node-externals 包
- visual-studio-code - VS Code:如何安排可以访问操作系统源的项目?
- c# - 从任务计划程序运行 C# 可执行文件时无法创建和保存 excel 文件