std::string::替换错误"no matching function for call"

std::string::replace "no matching function for call" error

本文关键字:function for call matching no 替换 错误 std string      更新时间:2024-04-29

我真的不知道如何让这个程序正常工作。目前唯一的问题是replace。我不能让它工作。我做错了什么?我们只允许使用if-elsewhile语句。

#include <iostream>
#include <string>
using namespace std;
int main() {
/*i becomes !
a becomes @
m becomes M
B becomes 8
o becomes .
append q*s */
string passWord;
cin >> passWord;
char chari = 'i';
int strLen = passWord.length();
int curPos = 0;
int chariIndex = passWord.find(chari);
while (curPos < strLen) {
if (passWord.find(chari)) {
passWord.replace(chariIndex, 1, '!');
cout << chariIndex << endl;
curPos += 1;
} 
}
cout << passWord << endl;
return 0;
}

您没有调用std::string::replace的任何重载。然而,由于您只替换单个字符,而不是replace,因此您可以简单地执行

passWord[chariIndex] = '!';

如果你想使用replace,那么你可以这样称呼它:

passWord.replace(chariIndex, 1, "!");

请注意,第三个参数是string,而不是char

此外,std::string::find不会像您在代码中所期望的那样返回bool。您需要将findstd::string::npos的结果进行比较:

if (passWord.find(chari) != std::string::npos) {
// found

如果将find的结果用作bool,则它将始终计算为true(除非在第0个索引处找到字符(。

相关文章: