如何使用字符串::与整数查找?C

How to use string::find with integer? C++

本文关键字:查找 整数 何使用 字符串      更新时间:2023-10-16

好吧,我当前正在编写一个小游戏机程序并遇到一个小问题:im构建一个程序,一个用户可以想到一个单词并将其转换为下划线(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)用作 ,也许我试图将其转换为整数,但我不知道

如何

ps:代码是德国人,因此对于德国人来说更容易理解

引起问题的部分应该像这样:

else {
        size_t pos = wort.find(eingabe);
        gesucht.erase(pos, 1);
        gesucht.insert(pos, 1, eingabe);
        cout << gesucht << endl;
    }

因为您要处理一个char而不是字符串,所以您应该使用.erase.insert

正确的过载

好吧,我解决了我的问题,我添加了一个1,所以知道应该添加多少个字符,因为eingabe是一个char。这就是工作代码的外观:

else {
    gesucht.erase(wort.find(eingabe), 1);
    gesucht.insert(wort.find(eingabe), 1, eingabe);
    cout << gesucht << endl;
}