C++未检查条件语句
C++ conditional statement not being checked
我已经为此挠头了一段时间,但我似乎无法弄清楚。
用户将输入一个介于 1 和 6 之间的数字。我正在进行检查,以确保他们输入的值是有效的输入。如果不是,它将继续提示他们,直到他们输入有效的输入。
我遇到的问题是,如果我输入任何整数值(这不是我想要的(,while 循环将终止。用户输入的整数必须介于 1 和 6 之间,然后应退出 while 循环(。
我希望有人能看到我看不到的东西。谢谢
#include <iostream>
#include <cmath>
using namespace std;
int ReadDouble(int option) {
while (cin.fail() != 0 && !(option > 0) && !(option <=6)) {
cin.clear();
cin.ignore(255, 'n');
cerr << "Cannot read input n";
cout << "Choose an option between 1 and 6: " << endl;
cin >> option;
}
cout << "This worked: " << endl;
return 0;
}
int main()
{
int prompt = NULL;
cout << "1. Cube" << endl;
cout << "2. Sphere" << endl;
cout << "3. Prism" << endl;
cout << "4. Cylinder" << endl;
cout << "5. Cone" << endl;
cout << "6. Quit" << endl;
cout << "Choose an option by typing in the corresponding number: ";
cin >> prompt;
ReadDouble(prompt);
}
您的问题如下所述: C++未检查的条件语句是您需要:!(option > 0) && !(option <=6)
更好的方法是执行以下操作:
while(!(cin >> prompt) || prompt < 0 || prompt > 6) cout << "Cannot read input.nChoose an option between 1 and 6: ";
现场示例
相关文章:
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ 中的"if"语句不会从左到右计算条件
- 优化/减少 if 语句中的条件表达式
- CPP 带有条件语句的内在事物
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 如果验证容器的大小并在同一条件语句下访问元素,这是很好的做法吗?
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 条件不变的 if 语句会减慢我的C++代码吗?
- C++ - 这个条件语句写得正确吗?还是有更有效的写法?
- C++17 if 语句,带有初始值设定项但没有条件
- if语句中满足的条件的索引
- C++:如何在 if 语句条件中使用指针
- 在 CPP 中将函数调用定时为 if 语句条件
- c++ 读取左 IF 语句条件和右语句条件
- C++忽略if语句条件
- 考虑到模板参数,正在更改if语句条件
- IF语句条件内的循环