user7981094
user7981094

Reputation:

Visual prints garbage letters - Caesar cipher excercise

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"


int main()
{
    char name[100];
    int key;
    printf("enter plaintext:\n");
    fgets(name, 100, stdin);
    int length = sizeof(name);
    printf("please enter key:");
    scanf("%d", &key);
    printf("plain text: %s\n", name);
    printf("ciphertext:");
    for (int i = 0; i < length; i++) {
         if (name[i] >= 65 && name[i] <= 90) {
             int c = (int)(name[i] - 'A');
             char d = 'A' + (char)((c + key) % 26);
             printf("%c", d);
        }
         else if (name[i] >= 97 && name[i] <= 122) {
                int c = (int)(name[i] - 'a');
                char d = 'a' + (char)((c + key) % 26);
                printf("%c", d);
        }
        else
           printf("%c", name[i]);
  }
    return 0;
}

Hello, So this is an exercise I have been trying to solve in the course "cs50" by Harvard. It's a ceaser cipher , it takes a string, a key, and prints the encryption: c=(pi+k) % 26

c - the final decrypted letter pi = the position the the letter ( a=0. b = 1..) k = the key

My program gives the right output, but the last row prints garbage chars: enter image description here

I though it was because memory allocation? But i haven't touched it yet, and I don't want to use the cs50.h package because I want to learn c the way it is, and not use "strings" variables like they do.

Any help would be appreciated.

Upvotes: 0

Views: 75

Answers (1)

true
true

Reputation: 41

Your issue is with the line

int length = sizeof(name);

the sizeof operator returns the size of a variable in bytes. In this case, since name is a char[100] the size of this object is 100 bytes. In the example you gave the plaintext (and ciphertext) were both much smaller so your loop ran over and started printing garbage memory (i.e. space that you allocated but didn't use to store the message).

What you need to use instead is

int length = strlen(name);

which returns the length of the string. Be sure to include the string.h header.

Upvotes: 2

Related Questions