【问题标题】:While loop always being executed once but works correctly on the second time. Help? [c++]While 循环总是执行一次,但第二次可以正常工作。帮助? [c++]
【发布时间】:2012-12-09 05:42:08
【问题描述】:

我在 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");

再次提前感谢。

【问题讨论】:

  • optketchup 是什么类型?此外,您需要一个等号来分配一个值,并且不推荐使用 homework 标签。
  • 简单地将您的字符串转换为小写或大写并仅针对“是”或“是”和“否”或“否”进行测试比测试每个大写/小写字母。
  • 不仅仅是他在测试每个大写/小写组合,不是一次,而是两次。经过所有这些测试,他会很累,以至于他需要那个三明治。
  • 完整代码不用展示:你展示的代码就够了,独立于其他代码

标签: c++


【解决方案1】:

while 中有一个分号 (';')。这就是问题所在。

不要写

while(.... lots of conditions ...);
{
    //stuff
}

while(.... lots of conditions ...)
{
    //stuff
}

请注意第二个中缺少;

除此之外,如果您必须检查单词Pneumonoultramicroscopicsilicovolcanoconiosis 怎么办。您最终会检查多少个大小写组合? 相反,将输入转换为大写并与大写 YESNOPNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS 进行比较。

【讨论】:

  • 你是对的!非常感谢。我一定是不小心把它放在那里了。非常感谢它现在有效!谢谢! :D
【解决方案2】:

执行单行代码的控制语句可以用两种不同的方式编写。

if (optketchup == "yes") {
  slcketchup = "with";
}
if (optketchup == "yes") slcketchup = "with";

以下代码也是有效的;不同的是,当optketchup 等于"yes" 时,没有任何指令可以执行。

if (optketchup == "yes");

其他控制语句也是如此,例如您的while

另外,= 是赋值运算符,而== 是比较运算符。当您想使用第一个时,您正在使用后者。
然后,正如其他人已经指出的那样,只需将optketchup 转换为小写:您只需将小写值与"yes" 进行比较,而不是检查使用小写/大写字符组合编写的“是”的任何可能变体。

【讨论】:

  • 谢谢! == 和 = 问题也把事情搞砸了。但主要错误已由 user93353 解决,但仍然非常感谢您! :D
猜你喜欢
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 2017-03-13
  • 1970-01-01
相关资源
最近更新 更多