0

My program compiles and runs but prints out the exact same text as i input in, that is, the ciphertext is same as the plaintext. TIA.

#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc,string argv[])
{
int k ;
if(argc ==2)
{
    k = atoi(argv[1]);
printf("plaintext:");
string s = get_string();
printf("\n");
printf("ciphertext:");
for(int i=0;i<strlen(s);i++)
 {
    char c = s[i];
    if ( islower(c))
    {
    printf("%c",((c +k -97)%26 + 97));
    }
      if ( isupper(c))
    {
    printf("%c",((c+k-65)%26 + 65));
    }

    else
    {
    printf("%c",c);
    }
   }
}
else
{
printf("usage: ./caesar k");
}
}
1

The main problem lies in your if/if/else structure. The first if statement will execute, independently of what follows. Then, the second if statement will be executed. If it's true, then the else code will be skipped, but if it's false, the else clause will execute.

So, for example, if the plaintext letter is a lower case letter, the first if clause will be true and will execute it's code. Then, the second if clause will be false, so it will not execute it's code block, but the else clause will be executed. That means that the lower case encoded letter will print, followed by the plaintext letter itself.

To use this sequence, it should have been if / else if / else. By not having the "else if", it disconnected the first if from the final else.

There are other issues, but you should be able to work them out.

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

You must log in to answer this question.

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