检查输入是否为特定类型并在特定范围内
Checking if an input is a particular type and in a particular range
我正在尝试测试用户输入的输入,以便我的程序不能中断。我正在使用的行是:
while (check != 0){
cout << "Please enter a number 1 - 4 (area of: circle, rectangle, triangle or quit)" << endl;
cin >> response;
if ((isdigit(response)) && ((response >= 1) && (response <= 4))){
check = 0;
}
else{
cout << "You did not enter a valid digit (1 - 4)" << endl;
check = 1;
}
} // End of while loop
我要做的是检查输入是否是一个数字(具体是整数),并且在1和4的范围内。由于某种原因,我输入的每个值都被认为使用此方法无效。为了得到我想要的结果,我应该改变或做些什么呢?(这样它就会检查输入是否是一个整数,以及这个整数是否在1到4之间(包括1和4))。
假设response
的类型为char
,则需要使用字符常量'1'
和'4'
,而不是整数常量1
和4
。
if ((isdigit(response)) && ((response >= '1') && (response <= '4'))){
if (response >= '1' && response <= '4')
就是你所需要的。如果输入的字符在正确的范围内,则必须是数字,因此不需要对isdigit
进行测试。多余的圆括号也不是。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 并行用于C++17中数组索引范围内的循环
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 如何修复错误,迭代器未在此范围内声明,并且迭代器未命名类型'
- 在 c++ 中确定某个值是否在该数据类型的最大范围内
- 为什么类型特征不适用于命名空间范围内的类型?
- 模板化函数范围内的条件模板化类型别名
- 更改if范围内变量的类型
- OpenCV-浮动数据类型和强度范围在0-255范围内的RGB通道
- 类模板实例化错误:未在此范围内声明类型
- 说明 资源路径位置类型 'UINT16_MAX' 未在此范围内声明
- 3 错误:错误:未在此范围内声明'Entry'。错误:模板参数 1 无效。错误:令牌之前声明中的类型无效'('
- 检查长类型数据是否在 int 范围内的便携式方法是什么?
- 如何检查两个数字是否在浮点类型的精度限制的有效数字"x"范围内?
- 在类范围内获取虚方法的类型
- 检查输入是否为特定类型并在特定范围内
- 在整数类型的整个范围内进行迭代
- 通过模板为项目范围内的唯一id自动增加类型
- 在编译时检查指定的值是否在类型的范围内