Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c++ - 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;
}

Input:

Hello World! Testing the Cryptography...

Output:

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

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

Why this ?i-o is comming out??

question from:https://stackoverflow.com/questions/65833357/char-outputting-random-characters-at-the-end-of-the-sentence

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For starters variable length arrays like this

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

is not a standard C++ feature.

You could use at least an array of objects of the type std::string like for example

std::string sMsg_Crypt[3];

Nevertheless the problem is that the array sMsg_Crypt[0] dies not contain a string. That is you forgot to append inserted characters in the array with the terminating zero character ''.

You could write after the for loop

sMsg_Crypt[0][length] = ''; 

provided that the array (if the compiler supports VLA) is declared like

char sMsg_Crypt[3][length+1];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...