C++ 中的输入检查问题
Problems with input check in c++
我希望程序循环直到输入有效(x 是 int,x>0),但是当我给它 1,1 时,我的程序接受输入,当我给它一个字符串时无限循环,重复"错误的输入!
#include <iostream>
using namespace std;
int main()
{
bool fail;
int x;
do{
cin >> x;
fail=(cin.fail() || x<=0);
if (fail){
cout << "Wrong input!" <<endl;
cin.clear();
};
}while(fail);
return 0;
}
在 if 语句中使用标准成员函数ignore
。例如
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),’n’);
或者只是
std::cin.ignore();
它用于跳过缓冲区中的无效符号。
您可以读取整行并使用字符串流转换该行:
#include <iostream>
#include <sstream>
int main()
{
bool fail;
int x;
do{
std::string line;
fail = ! getline(std::cin, line);
if( ! fail) {
std::istringstream s(line);
fail = ! (s >> x)
|| x < 0
|| ! s.eof(); // The entire line represents an integer
}
if(fail) {
std::cout << "Wrong input!" << std::endl;
};
} while(fail);
return 0;
}
相关文章:
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- 平衡括号问题为什么要检查它是否为空?
- 为什么当我从语句检查中删除"+ mod"时,以下程序给出错误的答案。问题链接:https://www.codechef.com/problems/FFC219B
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 仔细检查锁定问题,c++
- 双重检查创建单例问题的方法
- 检查 std::any 变量是否包含 std::string 时出现问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 六计算器问题.有人可以再次检查我的代码吗?
- 在检查传递函数标识符时是否获得模板参数时遇到问题
- 类型特征检查 CRTP 派生,在基类中,问题是未定义的类型
- 检查是否所有 std::元组元素都满足条件 + 设计问题
- 检查字符串中每个字符出现的问题
- 无锁的堆栈:在POP()期间检查危险指针时可见性问题
- 对简单的帐户检查程序有问题?程序返回编译错误,指出"no match for 'operator||' unsure of how to fix?"
- 检查内存泄漏问题
- 谁能想到一种方法,我可以错误地检查此问题
- openCV中的颜色检测-像素检查问题
- 编辑:检查文件是否为空时出现问题,我做错了什么
- C++ 中的输入检查问题