Search code examples
ccs50caesar-cipher

Caesar cipher outputs blank line


I am doing a problem set from the CS50 course and we have to implement Caesar's cipher. The following code works only with numbers (they remain the same as intended), when you put in a character, however, nothing is output. What's wrong?

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
//problem set requires arguments
int main (int argc, string argv [])
{
    int i = 0;

    if (argc != 2){
        printf ("Retry\n");
        return 1;
    } else {
        int x = atoi(argv [1]);
        //gets plaintext
        string a = get_string ("plaintext:");
        printf("ciphertext:");
        for (i = 0; i <= strlen(a); i++){
            //if character is a number it remains unchanged
            if (isdigit(a[i])){
                printf ("%c", a[i]);
            } else {
                if (isupper(a[i])){
                    //converts from ASCII index to alphabetical index
                    char y = a[i] - 65;
                    //Caesar cipher formula. If upper case remains upper case.
                    y = toupper(a[i] + x % 26);
                    //goes back ASCII
                    printf("%c", y + 65);
                    } else if (islower(a[i])){
                    //converts from ASCII index to alphabetical index
                    char t = a[i] - 65;
                    //Caesar cipher formula. If lower case remains lower case.
                    t = tolower(a[i] + x % 26);
                    //goes back to ASCII
                    printf("%c", t + 65);
                    }
                }
           }
        }
}

Solution

  • 65 is the ASCII value for letter 'A'. If you are working on lower case word, you would need 97, which is ASCII value for 'a'

    You have calculated t, but you didn't carry the result to the next line. Moreover, you have to take the modulus on the whole line. You are expecting that t is between 0 and 26, then you add it to 97

    char t = a[i] - 97;
    t = (t + x) % 26;
    printf("%c", t + 97);
    

    Also the for loop should go up to strlen(a). The last index in the string a is null-character, it should not be modified. You can also use 'a' instead of 97 here.

    for(i = 0; i < strlen(a); i++)
    {
        if(isupper(a[i]))   
        {
            char y = a[i] - 'A';
            y = (y + x ) % 26;
            printf("%c", y + 'A');
        }
        else if(islower(a[i])) 
        {
            char t = a[i] - 'a';
            t = (t + x )% 26;
            printf("%c", t + 'a');
        }
        else 
        {
            printf("%c", a[i]);
        }
    }