我在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”以外的任何内容,它仍然表示是。我试过用chars / characters来做,但是得到了相同的输出。有人可以帮我吗?

最佳答案

在典型的实现中,"A"'B'始终为true。

您还应该将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;
}

10-08 08:21
查看更多