不断收到错误代码:与"Ltrl == r_string[i]"中的"运算符=="不匹配
Keep getting error code: no match for 'operator==' in 'Ltrl == r_string[i]'
所以我制作了这段代码,以打印字母表中随机数量的字符,并告诉用户从列表中选择的两对字符的位置。我的问题是我不断收到几个错误,告诉我没有"'运算符=='的匹配项等等;我希望有人能告诉我我做错了什么以及如何解决这个问题。
这是我的代码和我收到的错误的屏幕截图。 在此处输入图像描述
#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::string
和char
- 两种类型,在任何地方都没有定义这样的运算符。问题源于这样一个事实,即std::string
和单个char
(不是 c 字符串(之间的比较不是由标准库(或您(定义的。这也许是因为这种比较如何运作并不明显。
如果要比较字符串和 c 字符串,只需使用 my_str == my_c_str
比较两者 - 或者,如果要手动比较单个字符,可以以类似的方式进行每次比较(使用每个单独的char
(。
尝试添加
#include <string>
到代码的顶部。
相关文章:
- 比较存储在 std::string 中的数据中的字节数
- std :: string中的数字
- 访问 std::string 中的元素,其中字符串的位置大于其大小
- 将std::string中的迭代字符与unicode C++进行比较
- 有选择地替换 C++ 中 std::string 中的 (") 双引号
- 将 C++ std::string 中的字符/字符序列替换为另一个字符序列
- 如何在C 中的文件中直接读取std :: String中的字符串
- 将 std::string 中的文本块向左移动 X 个字符
- 将 ASCII 文件读取到C++ std::string 中的最简单方法是什么?
- gSOAP:RPC截断std::string中的二进制数据
- C++:写入 std::string 中的特定索引位置
- (C++)如何从特定(结束)点查找 std::string 中的最后一个字符
- 如何在 C++ 中解析和验证 std::string 中的日期
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 替换由谓词确定的 std::string 中的字符的最 stl-ish 方法是什么
- 解析 std::string 中的两个或一个数字
- 合并排序 std:string 中的字符
- 使用 &front() 修改 std::string 中的基础字符数组
- std:string中的C++十六进制搜索失败
- 修剪std::string中的内部空白