0

This is the code I have:

// Osman Zakir
// 10 13 2016
// Introduction to Computer Science
// Problem Set 2, caesar.c
// Take the key for the cipher from the user as a command-line argument and use it to encrypt a message

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

int main(int argc, string argv[])
{
    if (argc == 1 || argc > 2)
    {
        printf("Error: Please input one number to use as key for cipher!\n");
        return 1;
    }
    printf("Enter plaintext to be shifted by %d positions\n", atoi(argv[1]));
    string plaintext = GetString();
    int key = atoi(argv[1]);
    for (int i = 0, n = strlen(plaintext); i < n; i++)
    {
        char ciphertext[n];
        if (isalpha(plaintext[i]))
        {
            ciphertext[i] = (plaintext[i] + key) % 26;
        }
        else
        {
            printf("%c", plaintext[i]);
        }
        printf("%c", ciphertext[i]);
    }
    printf("\n");
    return 0;
}

And I need to know what I'm doing wrong. The letters get turned into spaces or new lines for some reason, and only the non-alphabetic characters get printed (since I'm of course having it print them as they are without changing them).

1

Ok, First have a look at the if condition that you are implementing for checking if the character is an alphabet. Let us assume the letter at a certain time that is being ciphered is 'M' and the key is let us say '5'. Now if you check it, the int conversion of 'M' as per ASCII is 77( see : www.asciitable.com ).

Now take a look at what is happening inside that particular line of code. 5 is being added to 77 which is 82 and then the modulo operator comes. 82%26 = 4. When 4 is back type-casted into char it is EOT.

Long story short, no matter what your cipher text would never exceed the 25th ASCII character because of the modulo operator. So, you have to look for a way that would prevent that and that my friend is the essence of Caesar.

Hope this helps, if you satisfied with the answer then please upvote it and mark it as accepted. If there is any other query, please do ask.

2
  • With some help from my older brother, I added some stuff to the code to take care of that. There's still a problem, though. "abc" gets shifted to "TUV" instead of "nop". I added something else to the condition you mentioned above; in here: pastebin.com/1ZUmmE1v – Osman Zakir Oct 14 '16 at 0:29
  • Problem lies within the if conditions you are using, when you are checking for c > 'Z' , this condition is true for all the small case letters which didnot pass the first if condition. Rethink what you are doing here. – Jitesh Yadav Oct 14 '16 at 1:10

You must log in to answer this question.

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