我真的不知道如何让这个程序正常工作。目前唯一的问题是replace
。我不能让它工作。我做错了什么?我们只允许使用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;
}
您没有调用std::string::replace
的任何重载。然而,由于您只替换单个字符,而不是replace
,因此您可以简单地执行
passWord[chariIndex] = '!';
如果你想使用replace
,那么你可以这样称呼它:
passWord.replace(chariIndex, 1, "!");
请注意,第三个参数是string
,而不是char
。
此外,std::string::find
不会像您在代码中所期望的那样返回bool
。您需要将find
和std::string::npos
的结果进行比较:
if (passWord.find(chari) != std::string::npos) {
// found
如果将find
的结果用作bool
,则它将始终计算为true
(除非在第0个索引处找到字符(。