【问题标题】:Char outputting random characters at the end of the sentenceChar 在句尾输出随机字符
【发布时间】:2021-01-21 18:10:42
【问题描述】:
#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!测试密码学...'

地穴[0]:'Khoor Zruog! Whvwlqj wkh Fu|swrjudsk|...Çio'

为什么会出现这个Çi­o??

【问题讨论】:

  • 因为您的字符数组不是以空值结尾的。而且它们也是非标准C++,最好使用std::string
  • 你的空终止符在哪里?
  • 欢迎来到 Stack Overflow。请参阅How to Ask。另见Minimal Reproducible Example

标签: c++ arrays char c-strings


【解决方案1】:

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

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

不是标准的 C++ 功能。

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

std::string sMsg_Crypt[3];

但问题是数组sMsg_Crypt[0] 没有包含字符串。那就是您忘记在数组中附加插入的字符,以终止零字符'\0'

你可以在 for 循环之后写

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

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

char sMsg_Crypt[3][length+1];

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我知道你的意思。你知道你的意思。但要小心静电。这是一个重载的术语,在 C++ 中意味着非常不同的东西。请改用自动。
    猜你喜欢
    • 2014-12-17
    • 2020-01-27
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2011-09-16
    • 2014-10-21
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多