[英]std::string::replace “no matching function for call” error
I really don't know how to make this program work correctly.我真的不知道如何使这个程序正常工作。 The only problem at the moment is the replace
.目前唯一的问题是replace
。 I can't get it to work.我无法让它工作。 What am I doing wrong with it?我做错了什么? We're only allowed to use if
- else
, and while
statements.我们只允许使用if
- else
和while
语句。
#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;
}
You are not calling any of the overloads of std::string::replace
.您没有调用std::string::replace
的任何重载。 However, since you are only replacing a single character, instead of replace
, you could simply do但是,由于您只替换单个字符,而不是replace
,您可以简单地做
passWord[chariIndex] = '!';
If you want to use replace
then you could call it like this:如果你想使用replace
,那么你可以这样称呼它:
passWord.replace(chariIndex, 1, "!");
Note that the 3rd argument is a string
, not a char
.请注意,第三个参数是string
,而不是char
。
Also, std::string::find
does not return a bool
, as you seem to be expecting in your code.此外, std::string::find
不会返回bool
,正如您在代码中所期望的那样。 You need to compare the result of find
to std::string::npos
instead:您需要将find
的结果与std::string::npos
进行比较:
if (passWord.find(chari) != std::string::npos) {
// found
If you use the result of find
as a bool
, it will always evaluate to true
(unless you find the character at the 0th index).如果您将find
的结果用作bool
,它将始终评估为true
(除非您在第 0 个索引处找到字符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.