首页 > 解决方案 > 使用单个替换功能创建密码

问题描述

目前正在通过 C++ 课程。我必须使用字符串创建一个单词密码:字母表和密钥。为了用尽可能少的代码加密输入的单词,我创建了这个给出错误的解决方案:

没有匹配的调用函数std::basic_string<char>::find(std::string&, int&, int)

我不知道如何解决它,我也不知道我的想法是否会奏效,是否需要一些帮助。感谢您的关注 :)

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {

    string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    string key  {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
    string word_to_encrypt {};

    getline (cin,word_to_encrypt);

    for (int i=0;i<word_to_encrypt.size;i++){
        word_to_encrypt.replace (i,1,key,(alphabet.find(word_to_encrypt,i,1)),1);
    }

    cout<< word_to_encrypt;
}

标签: c++

解决方案


两个问题:

首先size是一个函数,而不是一个变量。因此你需要size().

其次std::string::find(),没有采用 astd::string和两个整数的重载:https.c_str() ://en.cppreference.com/w/cpp/string/basic_string/find,但您可以通过添加或来使用采用 CharT 的重载.data()

这至少编译:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {

    string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    string key  {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
    string word_to_encrypt {};

    getline (cin,word_to_encrypt);

    for (int i=0;i<word_to_encrypt.size();i++){
        word_to_encrypt.replace(i, 1, key, (
            alphabet.find(word_to_encrypt.c_str(), i, 1)),1);
    }

    cout<< word_to_encrypt;
}

推荐阅读