我在c ++中遇到了一个while循环问题。 while循环总是在第一次执行时,但是当程序到达while循环的cin时,while循环完美地工作,我想知道我做错了什么。提前致谢。如果问题是noobish,我很抱歉。我还是个初学者。
cout<<"Would you like some ketchup? y/n"<<endl<<endl<<endl; //Ketchup
selection screen
cin>>optketchup;
while (optketchup != "yes" && optketchup != "no" && optketchup != "YES" && optketchup != "Yes" && optketchup != "YEs" && optketchup != "yEs" && optketchup != "YeS"
&& optketchup != "yeS" && optketchup != "YeS" && optketchup != "yES" && optketchup != "y" && optketchup != "Y" && optketchup != "No" && optketchup != "nO"
&& optketchup != "NO" && optketchup != "n" && optketchup != "No");
{
cout<<"You have entered an entered "<<optketchup<<" which is an invalid
option. Please try again."<<endl;
cin>>optketchup;
}
if (optketchup == "yes" || optketchup == "YES" || optketchup == "Yes" || optketchup == "YEs" || optketchup == "yEs" || optketchup == "YeS"
|| optketchup == "yeS" || optketchup == "YeS" || optketchup == "yES" || optketchup == "y" || optketchup == "Y")
{
slcketchup == "with";
}
else
{
slcketchup == "without";
}
cout<<"Your sandwich shall be "<<slcketchup<<" ketchup."<<endl;
system ("pause");
再次感谢。
答案 0 :(得分:3)
while
中有分号(';')。这导致了这个问题。
不要写
while(.... lots of conditions ...);
{
//stuff
}
写
while(.... lots of conditions ...)
{
//stuff
}
请注意第二个中缺少;
。
除此之外,如果您必须检查单词Pneumonoultramicroscopicsilicovolcanoconiosis
,该怎么办?上面和下面有多少种组合小案你最终会检查?
相反,将输入转换为大写&amp;与大写YES
或NO
或PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS
进行比较。
答案 1 :(得分:1)
执行单行代码的控制语句可以用两种不同的方式编写。
if (optketchup == "yes") {
slcketchup = "with";
}
if (optketchup == "yes") slcketchup = "with";
以下代码也有效;不同之处在于,当optketchup
等于"yes"
时,没有任何指令可以执行。
if (optketchup == "yes");
其他控制语句也适用,例如while
。
此外,=
是赋值运算符,而==
是比较运算符。当你想使用第一个时,你正在使用后者
然后,正如其他人已经指出的那样,只需将optketchup
转换为小写:您只需将小写值与"yes"
进行比较,而不是检查&#34;是&#34;的任何可能变体。使用小写/大写字符混合编写。