c++ - 如何使用 string::find 与整数? C++

标签 c++ string insert

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

相关文章:

php - 使用 php 使用表单将记录添加到数据库

postgresql - 从 select 语句中调用返回值

c++ 写运算符>,我似乎不正确地接近比较,我该如何正确地做到这一点?

c# - 更改 C# 字符串中特定索引处字符的默认方法是什么?

java 程序未将所有数据集插入 mongodb 表

javascript - 找到两次相同的随机模式

c++ - C2146 : syntax : missing ')' before identifier 's'

c++ - 可移植设备的 Windows 句柄

C++ 模板类作为函数的参数

c++ - ijg 的 JPEG 支持 - 获取访问冲突