-6

这是我的代码。如果用户输入“是”或“是”,我希望我的 if 语句起作用。当我拿出|| 和“是”我的程序工作正常,当用户输入“是”时它工作。我想让我的程序变得更好,并拥有它,以便当他们输入“是”时工作。有人可以帮我解决这个问题吗?谢谢!

{

    cout<<"Would you like to begin?\n";


    cin>>answer;

    if (answer=="Yes" || "yes") {

        continue_1=true;

        google=false;

    }

    else {

        if (answer=="No" || "no" ) {

            cout <<endl<< "have a nice day\n";

            google= false;

            return 0;

        }
4

5 回答 5

4

您正在对字符串执行 or ,而不是在查询上执行 - 您想要:

    if (answer=="No" || answer=="no" ) {

为了更通用,尽管您可以将字符串转换为小写,然后将其与“no”进行比较,后者将为您处理“No”、“NO”和“no”。

一种常见的替代方法是只检查字符串中的第一个字符是 N 还是 n。这也包括诸如 Nope 之类的东西。

于 2013-12-23T14:09:20.373 回答
2
if (answer=="Yes" ||  answer == "yes")

您需要==在两个检查中使用。不幸的是,否则它不起作用

于 2013-12-23T14:09:28.030 回答
1

从哪里开始?

优先级 - 见http://en.cppreference.com/w/cpp/language/operator_precedence 字符串比较 = 见http://www.cplusplus.com/reference/cstring/strcmp/

并了解指针

于 2013-12-23T14:12:33.217 回答
0

正确的语法是:

if (answer=="Yes" || answer=="yes")

它不携带第一面的任何东西,OR 和 AND 可用于混合不同的值。像这样:

if (answer=="Yes" || otherAnswer=="no")
于 2013-12-23T14:10:31.070 回答
0

我宁愿用更少的分支来做:

cout<<"Would you like to begin?\n";
cin>>answer;

if (answer== "No" || answer== "no")
  return 0;

if (answer!= "Yes" && answer!= "yes" )
  return error; // only answer with yes or no

// here, we know that the answer is yes
于 2013-12-23T14:12:39.270 回答