C++ 条件语句未被检查
C++ conditional statement not being checked
我一直在为这个问题摸不着头脑,但似乎想不通。
用户将输入 1 到 6 之间的数字。我正在执行检查以确保他们输入的值是有效输入。如果不是,它将一直提示他们,直到他们输入有效的输入。
我遇到的问题是,如果我输入任何整数值(这不是我想要的。用户输入的整数必须在 1 到 6 之间,则 while 循环将终止,然后它应该退出 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);
}
这里提到的问题: 是您需要:!(option > 0) && !(option <=6)
更好的方法是:
while(!(cin >> prompt) || prompt < 0 || prompt > 6) cout << "Cannot read input.\nChoose an option between 1 and 6: ";
我一直在为这个问题摸不着头脑,但似乎想不通。
用户将输入 1 到 6 之间的数字。我正在执行检查以确保他们输入的值是有效输入。如果不是,它将一直提示他们,直到他们输入有效的输入。
我遇到的问题是,如果我输入任何整数值(这不是我想要的。用户输入的整数必须在 1 到 6 之间,则 while 循环将终止,然后它应该退出 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);
}
这里提到的问题:!(option > 0) && !(option <=6)
更好的方法是:
while(!(cin >> prompt) || prompt < 0 || prompt > 6) cout << "Cannot read input.\nChoose an option between 1 and 6: ";