0

My code encrypts the messages I enter; however, the capital letters are printed twice, first the ciphertext (which is correct) then the plaintext that was entered by the user (ex. "Hello" with a key of 3 prints as "KHhoor".) Why is that 'H' printing? Any help is much appreciated!

int key = atoi(argv[1]);
int i, n;
s = GetString();

for(i = 0, n = strlen(s); i < n; i++)
{
    if(isupper(s[i]))
    {
        printf("%c", (((s[i] + key - 'A') % 26) + 'A'));
    }
    if(islower(s[i]))
    {
        printf("%c", (((s[i] + key - 'a') % 26) + 'a'));
    }
    else
    {
        printf("%c", s[i]);
    }
}
1

It's your program structure. You are doing this:

if(x) do a;

if(y) do b; else do c;

A capital letter is represented as x. So, it does a. Then, since x is not y, it won't do b, but it will do c. Net, it does a and c. In your case, a and c are printf statements.

The else is only associated with the second if. The second if stands seperate from the first, and both if statements are assessed seperately. If you had done if / else if / else, it would probably be ok.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Now it works, thank you! – jmcsandiago Feb 22 '16 at 0:51

You must log in to answer this question.

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