c++ - 错误在哪里?显示字符串 C++ Vigenere 密码

标签 c++ string cout encryption

我正在尝试对 Vignère 密码进行编程,但我在加密文本方面遇到了问题。我已经完成了对字符串进行编码的功能,并且我认为它做得很好(我已经使用 Eclipse 对其进行了调试)但是我尝试使用 cout 在屏幕上显示它但没有出现任何内容。这是我的代码:

#include<iostream>
#include<string>
using namespace std;

const int MAX = 26;
typedef char TCuadrado[MAX][MAX];

void CuadradoVigenre(TCuadrado& cuadrado);
string CifrarMensaje(const TCuadrado& cuadrado, string clave, string texto);

int main(){
    TCuadrado cuadrado;
    CuadradoVigenre(cuadrado);
    for (int i = 0; i < MAX; i++){
        for(int j = 0; j < MAX; j++){
            cout << cuadrado[i][j];
        }
        cout << endl;
    }
    string res = CifrarMensaje(cuadrado, "VIGNERE", "CODIGO POLIALFABETICO");
    cout << res;
    return 0;
}


void CuadradoVigenre(TCuadrado& cuadrado){
    int letra = 0;
    for (int i = 0; i < MAX; i++){
        for(int j = 0; j < MAX; j++){
            cuadrado[i][j] = (char) letra + (int) 'A';
            letra++;
            if(letra > 25)
                letra = 0;
        }
        letra = i+1;
    }
}

string CifrarMensaje(const TCuadrado& cuadrado, string clave, string texto){
    string res = "";
    string nuevoConClave;
    int textoSize = texto.size();
    unsigned counterClave = 0;
    for (int i = 0; i < textoSize; i++){
        if(texto[i] != ' '){
            nuevoConClave[i] = clave[counterClave];
            counterClave++;
        }else{
            nuevoConClave[i] = ' ';
        }
        if(counterClave == clave.size())
            counterClave = 0;
    }

    for (int i = 0; i < textoSize;i++){
        if(texto[i] != ' ')
            res[i] = cuadrado[(int) nuevoConClave[i] - (int) 'A'][(int) texto[i] - (int) 'A'];
    }
    return res;
}

最佳答案

res[i] = .......

是你的错误所在。

您需要将它连接到字符串,因为它是空的并且其中没有任何内容。

所以每次运行res[0]res[1]res[2]等等,但实际上,您的字符串的长度始终为 0(意味着它没有任何索引)。

你应该使用:

res += .......

同样的问题是

nuevoConClave[i] = ....

在这里声明:

string nuevoConClave;

,但永远不要以任何方式修改它,并期望 nuevoConClave[i] 起作用?

希望对您有所帮助!

关于c++ - 错误在哪里?显示字符串 C++ Vigenere 密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18032449/

相关文章:

c# - 在 native 互操作中控制 WPF

c++ - 跟踪数据执行保护 (DEP)

java - 可能是二进制但通常是文本的数据的高效 JSON 编码

C - 如何通过直接输入一串数字和字符(符号)来创建计算器?

javascript - 从路径字符串获取所有父路径 - Javascript

通过从其他已初始化的字符串中复制索引字符形成的 C++ 字符串。无法使用 cout 打印新形成的字符串

C++ vector :std::out_of_range 错误

c - 输入后 Char 指针(字符串)数组崩溃?

c++ - 找到debugging printf去掉

c++ - 在 C++ 错误中打印数组