好的,我目前正在编写一个小的控制台程序,然后遇到了一个小问题:我正在构建一个程序,其中一个用户可以想到一个单词并将其翻译为下划线(Word = ____),而另一个用户则必须猜测字母(用户猜测) W;程序先删除_,然后插入W“W___”,直到出现完整单词为止),现在我的代码如下所示:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string wort;
cout << "Bitte gebe ein Wort ein: ";
cin >> wort;
string gesucht = "";
if (wort.length() == 0 || wort.length() > 63) {
cout << "Bitte gebe ein gueltiges Wort ein.\n";
}
else {
for (unsigned int a = 1; a <= wort.length(); a++) {
gesucht.insert(0, "_");
}
}
cout << "Folgendes Wort wird gesucht: " << gesucht << endl;
int versuche = 11;
char eingabe;
cin >> eingabe;
if (wort.find(eingabe) == string::npos) {
versuche--;
cout << "Folgendes Wort wird gesucht: " << gesucht << ", du hast noch " << versuche << " Fehlversuche.\n";
}
else {
gesucht.erase(wort.find(eingabe));
gesucht.insert(wort.find(eingabe), eingabe);
cout << gesucht << endl;
}
return 0;
}
问题是这部分:
else {
gesucht.erase(wort.find(eingabe));
gesucht.insert(wort.find(eingabe), eingabe);
cout << gesucht << endl;
}
它不会让我将
wort.find(eingabe)
用作Where,所以也许我正在尝试将其转换为整数,但我不知道如何PS:该代码为德语,因此对于德国人来说更容易理解
最佳答案
导致问题的部分应如下所示:
else {
size_t pos = wort.find(eingabe);
gesucht.erase(pos, 1);
gesucht.insert(pos, 1, eingabe);
cout << gesucht << endl;
}
因为要处理的是单个字符而不是字符串,所以应正确使用
.erase
和.insert
重载
关于c++ - 如何使用string::find与整数? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623734/