维杰尼雷密码错误在C++

Vigenere Cipher error in C++

本文关键字:错误 C++ 密码 雷密码      更新时间:2023-10-16

我正在用c ++创建一个vigenere密码,当我运行代码时,它有一个错误说:(按重试调试应用程序)控制台应用程序 2.exe 触发了断点。调试断言失败!程序: C:\Windows\system32\MSVCP140D.dll文件: c:\program files (x86)\Microsoft Visual Studio 14.0\vc\include\xstring行: 1681表达式:字符串下标超出范围有关程序如何导致断言的信息失败,请参阅有关断言的视觉C++文档。(按重试以调试应用程序)控制台应用程序 2.exe 触发了断点。程序"[3668] ConsoleApplication2.exe"已退出,代码为 -1073741510 (0xc000013a)。这是代码:

#include <iostream>
#include <string>
#include "stdafx.h"

using namespace std;
int main()
{
    string plaintext, key, Result;
    int k = 0;
    cout << "Enter the plain text: ";
    cin >> plaintext;
    cout << "Enter the key word: ";
    cin >> key;
    for (int i=0; i<plaintext.length(); i++)
    {
        Result[i] = (((plaintext[i] - 97) + (key[k] - 97)) % 26) + 97;
        k++;
        if (k == 6)
            (k = 0);
    }
    cout << "    nnn";
    for (int i=0; i<plaintext.length(); i++)
        cout <<" "<< Result[i];
    cout << "nnnn";
    return 0;
}

错误出在 for 语句中for (int i=0; i<plaintext.length(); i++)它说了一些关于<符号的信息,我不知道为什么。有什么帮助吗?谢谢:)>

您从不为Result设置大小,i因此您在

Result[i] = (((plaintext[i] - 97) + (key[k] - 97)) % 26) + 97;

无效。 您需要首先设置Result的大小。 你可以使用类似的东西

string plaintext, key, Result;
int k = 0;
cout << "Enter the plain text: ";
cin >> plaintext;
cout << "Enter the key word: ";
cin >> key;
Result.resize(plaintext.size());
//...

在语句中

key[k]

你如何检查索引 k