凯撒密码程序中"Debug Assertion Failed!"问题

"Debug Assertion Failed!" issue in a Caesar Cipher program

本文关键字:Failed 问题 Assertion Debug 程序 凯撒 密码      更新时间:2023-10-16

你好!

目前正在C++创建一个程序,其目的是使用Caesar Cipher加密短语,并且在Visual Studio 2017社区中多次尝试调试后无法弄清楚这里的问题是什么Microsoft。

问题

reference operator[](const size_type _Off)
    {   // subscript mutable sequence
    _IDL_VERIFY(_Off <= this->_Mysize(), "string subscript out of range"); //(Here, a breakpoint is triggered)
    return (this->_Myptr()[_Off]);
    }
错误

列表中没有显示任何错误或警告,但在运行时,我的程序"跳转"到一个名为"xstring"的库中并在此函数中停止(请参阅代码(。

调试输出

    Debug Assertion Failed!
Program: C:Windowssystem32MSVCP140D.dll
File: c:program files (x86)microsoft visual studio2017communityvctoolsmsvc14.10.25017includexstring
Line: 2944
Expression: string subscript out of range
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
<小时 />

加密功能

int encrypt(string plainText, string cipherText, int length, int key)
{
    int charLength = (int)plainText.length();
    if (key < 0)
    {
        return -1;
    }
    for (int i = 0; i < charLength; i++)
    {
        if (isalpha(plainText[i]))
        {
            plainText[i] = tolower(plainText[i]);
            cipherText[i] = plainText[i];
            for (int j = 0; j < key; j++)
            {
                if (cipherText[i] == 'z')
                {
                    cipherText[i] = 'a';
                }
                cipherText[i]++;
            }
        }
        
    }
    return charLength;
}

在写入密文之前,您从不检查密文的大小。你确定它的大小合适吗?鉴于您遇到的错误和我们获得的少量信息,这将是原因。

尝试添加

cipherText.resize(charLength);

int charLength = (int)plainText.length();之后