char在句末输出随机字符

Char outputting random characters at the end of the sentence

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

using namespace std;

void crypt(char* sMsg)
{
    cout << "Original Message: '" << sMsg << "'" << endl;

    int length = strlen(sMsg);
    char sMsg_Crypt[3][length];
    /*  sMsg_Cryp[3]
        [0] CRYPT LETTERS, ASCII + 3
        [1] INVERT CHAR
        [2] HALF+ OF SENTENCE, ASCII - 1
    */
    
    for (int i=0; i<length; i++)
    {
        if (isalpha((int)sMsg[i]))
            sMsg_Crypt[0][i] = sMsg[i] + 3; // DO ASCII + 3
        else
            sMsg_Crypt[0][i] = sMsg[i];
    }

    cout << "Crypt[0]: '" << sMsg_Crypt[0] << "'" << endl;
}

int main()
{
    char sMsg[256];
    cin.getline(sMsg,256);
    crypt(sMsg);
    
    return 0;
}

输入:

Hello World! Testing the Cryptography...

输出:

Original Message: 'Hello World! Testing the Cryptography...'

Crypt[0]: 'Khoor Zruog! Whvwlqj wkh Fu|swrjudsk|...Çi­o'

为什么这个 Çi­o 出来了??

对于像这样的初学者可变长度数组

int length = strlen(sMsg);
char sMsg_Crypt[3][length];

不是标准的 C++ 功能。

您至少可以使用 std::string 类型的对象数组,例如

std::string sMsg_Crypt[3];

然而问题是数组 sMsg_Crypt[0] 不包含字符串。那是你忘了在数组中附加插入的字符和终止零字符 '[=16=]'.

你可以在 for 循环之后写

sMsg_Crypt[0][length] = '[=12=]'; 

前提是数组(如果编译器支持VLA)声明为

char sMsg_Crypt[3][length+1];

首先,您不能像这样定义静态 char 数组:char sMsg_Crypt[3][length];。这是因为 length 不是 const 类型,这意味着数组的大小将为 sMsg_Crypt[3][0] (这是因为在编译时不知道大小)。在 MSVC 中,它会标记错误(通过 IntelliSense)。由于您事先知道大小 (256),因此可以将 length 替换为 256.

第二个事实是您正在使用 C++ 并且您可以访问 std::string。因此,不使用 char 缓冲区,而是使用 std::string。它看起来像这样:std::string sMsg_Crypt[3];

最后一个事实是,要正确读取字符串,它需要以 null 结尾(末尾为“\0”)。这意味着结束字符必须是“\0”。对于 std::string,它会为您完成。