C++未检查条件语句

C++ conditional statement not being checked

本文关键字:语句 条件 检查 C++      更新时间:2023-10-16

我已经为此挠头了一段时间,但我似乎无法弄清楚。

用户将输入一个介于 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: ";

现场示例