谁能帮我处理C++中的语句和字符串

Could anyone help me with if statements and strings in C++?

本文关键字:语句 字符串 C++ 处理      更新时间:2023-10-16

我在 c++ 中的 if 语句和字符串/字符方面遇到了一些麻烦。这是我的代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    cout << "-----------------------------" << endl;
    cout << "|Welcome to Castle Clashers!|" << endl;
    cout << "-----------------------------" << endl;
    cout << "Would you like to start?" << endl;
    string input;
    cout << "A. Yes ";
    cout << "B. No " << endl;
    cin >> input;
    if(input == "a" || "A"){
        cout << "Yes" << endl;
    }else{
        if(input == 'b' || 'B'){
            return 0;
        }
    }
    return 0;
}

在我的 if 语句中,它检查字符串输入是否等于 yes,如果不是,则应转到 else 语句。这就是麻烦开始的地方,一旦我在控制台中运行我的程序,当我键入除"a"或"A"以外的任何内容时,它仍然说是。我尝试使用字符/字符执行此操作,但我得到相同的输出。谁能帮我?

它应该是input == "a" || input == "A" .您必须单独测试每个案例。现在你的代码等效于 (input == "a") || "A" ,它的计算结果是true,因为"A"衰减到非零指针。

"A"'B'在典型实现中将始终为真。

您还应该将input与他们进行比较。

此外,似乎不支持将std::stringchar进行比较,因此您还应该对bB使用字符串文本。

Try this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
    cout << "-----------------------------" << endl;
    cout << "|Welcome to Castle Clashers!|" << endl;
    cout << "-----------------------------" << endl;
    cout << "Would you like to start?" << endl;
    string input;
    cout << "A. Yes ";
    cout << "B. No " << endl;
    cin >> input;
    if(input == "a" || input == "A"){
        cout << "Yes" << endl;
    }else{
        if(input == "b" || input == "B"){
            return 0;
        }
    }
    return 0;
}

C 没有"真正的"布尔值 - 相反,任何等于 0 的东西都被认为是的,任何与此不同的值都被认为是真的。虽然C++引入了bool类型,但出于兼容性原因,它仍然保持旧的 C 行为。

正如 Cornstalk 所说,你的(input == "a" || "A")((input == "a") || ("A")) 相同,并且"A" != 0,所以它总是计算为 true - 这就是为什么它总是会进入 if 块。 你想要的是:

if (input == "a" || input == "A")

下一条语句也是如此(将其与"B"进行比较),但还有一个额外的问题:您使用单引号 ( ' ) 而不是双引号 ( "),这使它成为char而不是string。要使两个变量的类型相同,只需使用双引号,结果如下:

if(input == "b" || input == "B")