【问题标题】:Vigenere Cipher error in C++C++ 中的 Vigenere 密码错误
【发布时间】:2016-02-24 02:53:06
【问题描述】:

我在 c++ 中创建了一个 vigenere 密码,当我运行代码时出现错误提示:(按重试以调试应用程序) ConsoleApplication2.exe 已触发断点。 调试断言失败! 程序:C:\Windows\system32\MSVCP140D.dll 文件:c:\program files (x86)\microsoft visual studio 14.0\vc\include\xstring 线路:1681 表达式:字符串下标超出范围 有关您的程序如何导致断言的信息 失败,请参阅有关断言的 Visual C++ 文档。 (按重试调试应用程序) ConsoleApplication2.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 << "    \n\n\n";
    for (int i=0; i<plaintext.length(); i++)
        cout <<" "<< Result[i];
    cout << "\n\n\n\n";

    return 0;
}

错误出现在 for 语句 for (int i=0; i&lt;plaintext.length(); i++)它说了一些关于

【问题讨论】:

    标签: c++ debugging visual-studio-2015 console-application vigenere


    【解决方案1】:

    您从未为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());
    //...
    

    【讨论】:

    • 我必须复制这个 Result.resize(plaintext.size());还是还有更多? @NathanOliver
    • @warren 从我看到的情况来看是的,但您可能还有其他问题。这只是修复了访问冲突。
    【解决方案2】:

    在声明中

    key[k]
    

    如何检查索引 k key.length() ?变量k 有界 [0,5] 但你怎么知道 `key.length()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多