jaxk
jaxk

Reputation: 3

Why is my Caesar solution (CS50) double-typing uppercase characters?

My program can correctly encrypt lowercase letters, but for uppercase the output will double-type characters. For example, if I put the input in as "BARFOO", my program will output "EBDAURIFRORO". Code is shown below.

printf("ciphertext: ");
for (int i = 0, n = strlen(plain); i < n; i++) 
{
    if (isalpha(plain[i]) && isupper(plain[i])) //problem must be here
    {
        int c = 65;
        printf("%c", (plain[i] - c + key) % 26 + c); 
    }
    
    if (isalpha(plain[i]) && islower(plain[i])) //this works
    {
        int c = 97;
        printf("%c", (plain[i] - c + key) % 26 + c);
    }
    
    else //this preserves punctuation, space, etc.
    {
        printf("%c", plain[i]);
    }
}
printf("\n");

What I'm trying to do in the first if loop is check for uppercase alphabetic characters. I then iterate over each character, converting it to an alphabetic index, where 'A' is indexed at [0], B at [1], and so on. At the end you can see that I convert it back to the Ascii index. Why is it doing this only with uppercase letters? Is my math wrong? For lowercase letters, the math is basically the same, but it's behaving as it should. I'm assuming it's a problem with my for loop, but I'm not sure what I have to do to change it.

Upvotes: 0

Views: 146

Answers (1)

tgarm
tgarm

Reputation: 493

Your first "if" is independent. So when input is uppercase, it will encode and show in the first "if", and then bypass and show in the "else" because it's not uppercase.

You can make the "else" just bypass every non-alpha characters instead of just bypass non-lowercase characters to solve this problem, like this:

printf("ciphertext: ");
for (int i = 0, n = strlen(plain); i < n; i++)
{
    if (isalpha(plain[i]))
    {
        if(isupper(plain[i])) //problem must be here
        {
            int c = 65;
            printf("%c", (plain[i] - c + key) % 26 + c);
        }else{
            int c = 97;
            printf("%c", (plain[i] - c + key) % 26 + c);
        }

    }else //this preserves punctuation, space, etc.
    {
        printf("%c", plain[i]);
    }
}
printf("\n");

Upvotes: 1

Related Questions