undefined behavior (extra symbols) added to my char string when printng with printf in C program

55 Views Asked by At

I wrote this program to help someone else and as a learning exercise but now I am confused as to why the strange additions are happening? Help is greatly appreciated

#include <stdio.h>
#include <ctype.h>

typedef struct
{
    char str[1000];
} arrType;

typedef struct
{
    char *str;
} ptrType;

ptrType message = {"start"};

int main()
{
    int choice;
    int i;
    char temp;
    char begmessage[1000];
    char endmessage[1000];
    printf("Would you like to (1) encrypt or (2) decrypt?: ");
    scanf("%i", &choice);
    scanf("%c", &temp); // temp statement to clear buffer
    printf("You chose: %d\n", choice);
    printf("Type your message: ");
    scanf("%[^\n]", begmessage);
    ptrType message = {begmessage};
    printf("\nThe message you typed is %s \n", message.str);
    if (choice == 1) 
    {
        for (i = 0; (i < 1000 && message.str[i] != '\0');) 
        {
            if (isalnum(message.str[i])) 
            {
                endmessage[i] = putchar((message.str[i] + 1));
                i +=1;
            } 
            else 
            {
                endmessage[i] = putchar((message.str[i])); i +=1;
            }
        }
    printf("\nYour message is now: %s\n", endmessage);
    }
    if (choice == 2) {
        for (i = 0; (i < 1000 && message.str[i] != '\0');) 
        {
            if (isalnum(message.str[i])) 
            {
                endmessage[i] = putchar((message.str[i] - 1));
                i +=1;
            } 
            else 
            {
                endmessage[i] = putchar((message.str[i])); i +=1;
            }
        }
    printf("\nYour message is now: %s\n", endmessage);

    } 

}

Here is the output:

Would you like to (1) encrypt or (2) decrypt?: 1 You chose: 1 Type your message: High Tower

The message you typed is High Tower Ijhi Upxfs Your message is now: Ijhi Upxfs���

Would you like to (1) encrypt or (2) decrypt?: 2 You chose: 2 Type your message: Ijhi Upxfs

The message you typed is Ijhi Upxfs High Tower Your message is now: High Tower���

this line "High Tower" comes from where? and on the last line where does the "���" come from. I did a search on stackoverflow and the internet but the symbol � is not recognized...

Ran the program again and got similar results:

Would you like to (1) encrypt or (2) decrypt?: 1 You chose: 1 Type your message: High Tower

The message you typed is High Tower Ijhi Upxfs Your message is now: Ijhi Upxfs�;�

Would you like to (1) encrypt or (2) decrypt?: 2 You chose: 2 Type your message: Ijhi Upxfs

The message you typed is Ijhi Upxfs High Tower Your message is now: High Tower@

0

There are 0 best solutions below