Search code examples
ccaesar-ciphercs50

Weird Output with caesar.c


Code from my caesar.c file

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>


int main(int argc, string argv[])
{
    // get a string from the user, a non-negative integer.
    if (argc != 2 || atoi(argv[0]) < 0)
    {
        printf("Usage: ./caesar cyphertext\n");
        return 1;
    }

    // create the cyphertext.
    int cyphertext = atoi(argv[1]);

    // declare plaintext input.
    string plaintext = GetString();

    // get the plaintext encrypted using the key.
    for (int i = 0, n = strlen(plaintext); i < n; i++)
    {
        if (plaintext[i] > 'A' && plaintext[i] <= 'Z')
        {
            plaintext[i] = (plaintext[i] - 'A' + cyphertext) % 26;
        }   
            else if (plaintext[i] >= 'a' && plaintext[i] < 'z')
            {
                plaintext[i] = (plaintext[i] - 'a' + cyphertext) % 26;
            } 
    }
    {
        // print out the results of the cypher and plaintext.
        printf("%s\n", plaintext);
    }
    return 0;   
}

Output I type in ./caesar 13 and then on the following line I type in the word "hello". Hello then returns several small boxes with small letters and numbers in them. I could not copy and paste the exact characters.

Edit:

Thanks for the help. I cleaned up as per your help and now when I run the check50 program

check50 2014/x/pset2/caesar caesar.c

I get the following error:

:( encrypts "BARFOO" as "EDUIRR" using 3 as key
   \ expected output, but not "EAUIRR\n"

yet when I run the word BARFOO with the 3 as a key I do in fact get the output as EAUIRR.


Solution

  • You made mistake at caesar encryption.

    plaintext[i] = (plaintext[i] - 'A' + cyphertext) % 26;
    

    should be

    plaintext[i] = 'A' + ((plaintext[i] - 'A' + cyphertext) % 26);
    

    and

    plaintext[i] = (plaintext[i] - 'a' + cyphertext) % 26;
    

    should be

    plaintext[i] = 'a' + ((plaintext[i] - 'a' + cyphertext) % 26);
    

    EXPLANATION:

    Let consider the case plaintext[i]="h".

    plaintext[i] - 'a' 
    

    makes 7. ('h' - 'a')

    (plaintext[i] - 'a' + cyphertext) % 26
    

    makes 20. ((7 + 13) % 26)

    The character ,whose code is 20, is a control code "DC4" and it is not printable.

    This is why you see "small boxes with small letters and numbers in then".

    You can fix this problem by adding code ot 'a' to 20.