0

I'm almost done working on my caesar program, but whenever I try to print out a char, it returns a weird box symbol with numbers inside it or a diamond with a question mark inside, depending on the size of the key. When I try to print out an integer, it works fine and prints within the bounds of alphabetical letters (0-25 in this case). My code is as follows:

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

int main(int argc, string argv[])
{
    if (argc != 2)
{
    printf("Enter your key after ./caesar\n");
    return 1; 
}

int key = atoi(argv[1]);

printf("Enter plaintext: ");
string p = GetString();

int i;

for (i = 0; i < strlen(p); i++)
{
    int code = (p[i] + key) % 26;
    if (isalpha(p[i]))
    {

        if (isupper(p[i]))
        {
            printf("%c", (code + key) % 26);
        }

        if (islower(p[i]))
        {
            printf("%c", (code + key) % 26);
        }
    }
printf("\n");
}

}

What am I doing wrong?

1

The formula, as it is in the specs, and as you're using it, only works if the alphabetic chars are in a range 0 - 25. That is, 'a' == 0, 'b' == 1, etc.

That's not the case because that's not the ASCII value of the alphabetic chars. You have to account for that. Get an ASCII table, look at the values the letters have, and then "translate" the ASCII value to a range of 0 - 25.

Also, why are you adding key twice?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .