不断收到错误代码:与"Ltrl == r_string[i]"中的"运算符=="不匹配

Keep getting error code: no match for 'operator==' in 'Ltrl == r_string[i]'

本文关键字:string 中的 不匹配 运算符 错误代码 Ltrl      更新时间:2023-10-16

所以我制作了这段代码,以打印字母表中随机数量的字符,并告诉用户从列表中选择的两对字符的位置。我的问题是我不断收到几个错误,告诉我没有"'运算符=='的匹配项等等;我希望有人能告诉我我做错了什么以及如何解决这个问题。

这是我的代码和我收到的错误的屏幕截图。 在此处输入图像描述

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
int n;
string Ltr1, Ltr2;
int i=0;
char alphabet[26];
char r_string[200];
srand(time(0));
cout << "How many letters do you want in your random string (no less than 0, no more than 100): ";
 cin >> n;
for (int i=0; i<=25; i++)
 alphabet[i] = 'a' + i;
while(i<n) {
    int temp = rand() % 26;
    r_string[i] = alphabet[temp];
    i++;
}
for(i=0; i<n; i++)
    cout<<r_string[i];
    cout<<"nn";
cout<<"nn What letter pair would you like to find? ";
cin>>Ltr1>>Ltr2;
 for (i=0; i<n; i++)
  if ((Ltr1 == r_string[i]) && (Ltr2 == r_string[i+1])) {
    cout<<" The pair is in the string starting at character number"<<i+1<<" in the string. n";
}else{
    cout << "The letter pair "<< Ltr1, Ltr2 <<" is not in this string. n";
    }
}

在C++中,涉及非指针、非基本类型的运算符(如==!=+等(必须在某处定义和实现(还有隐式可转换类型的问题,但这超出了这个问题的范围(。例如,采用以下代码:

#include <string>
int main() {
    std::string my_str = "Hello world!", other_str = "Hello!";
    const char *my_c_str = "Hello world!", my_char = 'H';
    my_str == other_str;  //OK:  calls operator==(std::string, std::string)
    my_str[0] == my_char; //OK:  calls operator==(char, char)
    my_str == my_c_str;   //OK:  calls operator==(std::string, char*)
    my_str == my_char;    //bad: attempts to call operator==(std::string, char), which is not defined
}

在这种情况下,您正在尝试比较(与operator==(std::stringchar - 两种类型,在任何地方都没有定义这样的运算符。问题源于这样一个事实,即std::string和单个char(不是 c 字符串(之间的比较不是由标准库(您(定义的。这也许是因为这种比较如何运作并不明显。

如果要比较字符串和 c 字符串,只需使用 my_str == my_c_str 比较两者 - 或者,如果要手动比较单个字符,可以以类似的方式进行每次比较(使用每个单独的char(。

尝试添加

#include <string> 

到代码的顶部。