【问题标题】:C++ if statements with strings only give one answer带有字符串的 C++ if 语句只给出一个答案
【发布时间】:2014-09-06 03:22:18
【问题描述】:

所以,我试图写一个文本冒险的东西,每当我尝试将字符串与消息进行比较时,无论我写什么,我总是会得到相同的输出......我已经搜索和搜索,并且无法找到答案...我有使用 Java、LUA 和一些 HTML 编程的经验...也许我正在尝试做的事情与 Java 的方式太相似了?好吧,这里有一些代码可能最终会有所帮助。

string sex;

cout << "Would you like to be a boy or a girl?" << endl;
cin >> sex;
cout << sex;
//statement to declare what you are...
if (sex == "boy" || "Boy"){
    cout << "You have chosen to be a boy!" << endl;
}
else if (sex == "girl" || "Girl"){
    cout << "You have chosen to be a girl!" << endl;
}
else{
    create();
}

我们将不胜感激任何形式的帮助。谢谢。

【问题讨论】:

  • c 中的字符串不同。尝试使用strcasecmp

标签: c++ string if-statement compare std


【解决方案1】:

改变

if (sex == "boy" || sex == "Boy"){
    cout << "You have chosen to be a boy!" << endl;
}
else if (sex == "girl" || sex == "Girl"){
    cout << "You have chosen to be a girl!" << endl;
}

if (sex == "boy" || sex == "Boy"){
    cout << "You have chosen to be a boy!" << endl;
}
else if (sex == "girl" || sex =="Girl"){
    cout << "You have chosen to be a girl!" << endl;
}

原因是if (sex == "boy" || "Boy") 声明,第二部分将始终评估为真。

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 2014-12-13
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多