好吧,我目前正在编写一个小控制台程序并遇到了一个小问题:我正在构建一个程序,其中一个用户可以想到一个单词并将其翻译成下划线 (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/