首页 > 解决方案 > 如何在来自不同类的字符串或字符数组中显示特定字符

问题描述

C++ 初学者和在这里编程。如果这听起来很愚蠢,那么你知道为什么。我正在尝试将变量与字符串或字符数组中的特定字符进行比较。当我将它与 . 我想使用“if”功能,但还有其他方法吗?C++

我试过做 if(variable == Obj.ArrayofString[0][1])if(variable == b[0][0])没有用

#include "DataBase.h"
#include <iostream>
#include <string>

using namespace std;

string input;
string b[] = {"Lol","Fight"};

int main()
{
    DataBase Bo;

    cout << "Type a letter" << endl;
    cin >> input;

    if (input == Bo.Words[0]){
        cout << "Got one" << endl;
    }


    cout << Bo.Words[0][0];


    return 0;

}

**enter code here**

当我尝试将特定变量与数组中特定元素的特定字符进行比较时,出现错误。请帮忙。检查“构建消息”选项卡底部的红线

'operator==' 不匹配(操作数类型是 'std::_cxxll::string {aka std::_cxll 和其他一些东西

标签: c++

解决方案


这里的问题是您正在尝试将 astring与 a进行比较char。这两种是不同的类型。例如,您的输入可能包含多个字母。

解决方案很简单:取输入字符串的第一个字符。

if (input[0] == Bo.Words[0][0]){
    cout << "Got one" << endl;
}

我假设这里Bo.Words[0]也是 type std::string。另外,我指的是您的链接代码。在您发布的代码中,您有Bo.Words[0]而不是Bo.Words[0][0].


推荐阅读