当我输入“ 1”(不带引号)作为输入时,它将带我到错误菜单(无效输入)。
重新措辞: 当我运行该程序时,在初始形状提示菜单或“无效输入”菜单上,如果输入“ 1”,则无法继续选择。
有人对这里发生的事情有了解吗?
#include <iostream>
#include <string>
#include <limits>
using std::cout;
using std::cin;
using std::string;
using std::endl;
int main()
{
string username;
cout<<"Hello.\nMy name is Pythagoras.\nI will be helping you build shapes today.\n\nWhat is your name?\n"<<endl;
cin>>username;
int shapeselect;
cout<<"Hello, "<<username<<".\nWhat shape would you like to build today?\n1)Rectangle/Square\n2)Triangle\n3)Random!\n(Please select a number.)\n"<<endl;
cin>>shapeselect;
while (shapeselect!=1||shapeselect!=2||shapeselect!=3)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<"Sorry, "<<username<<", your entry was invalid. Please select a valid number.\n";
cout<<"What shape would you like to build today, "<<username<<"?\n1)Rectangle/Square!\n2)Triangle!\n3)Random!"<<endl;
cin>>shapeselect;
}
if (shapeselect==1)
{
int width;
cout<<"\nPlease enter the desired WIDTH of the rectangle, between 4 and 10.\n(Please select a number.)\n";
cin>>width;
cout<<"\nYou have selected a width of "<<width<<"."<<endl;
int length;
cout<<"\nPlease enter the desired LENGTH of the rectangle, between 4 and 10.\n(Please select a number.)\n";
cin>>length;
cout<<"\nYou have selected a length of "<<length<<"."<<endl;
if (width==length)
{
cout<<"Please note that you have selected a width of "<<width<<" and a length of "<<width<<".\nNote that this shape will be a square.\n"<<endl;
}
}
return 0;
}
答案 0 :(得分:1)
据我了解,当shapeselect为1,2,3以外的某个数字时,您需要执行while循环。
要解决该问题,请在条件为while时用AND门替换所有OR门。
原因:因为,或门的任何一个输入为真时,输出为真。因此,如果shapeselect等于1,则它将不等于2和3,这使得shapeshelect!=2
和shapeselect!=3
的计算结果为true。
无论您输入哪个数字,while循环都将始终运行。