0

below is my code for caesar's cipher but for some reason it doesn't print anything.

/* a program, caesar, that encrypts messages using Caesar’s cipher*/

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

int main(int argc, string argv[])
{
    //Checks for argument count
    if(argc < 2 || argc > 2)
    return 1;

    //converts string to int
    int k = atoi(argv[1]);

    //gets plaintext to encipher from user
    char* Plain_text = get_string(); 
    for(int i = 0, n = strlen(Plain_text); i < n; i++)
    {
        //checks if plaintext contains space
            if(Plain_text[i] == ' ')
            {
                printf("%c", Plain_text[i]);
            }
            else
            {
                //checks for alphabetic characters
                if(isalpha(Plain_text[i]))
                {
                    //iteration for wraparound 
                    for(int j = 65; j < 65 + 26; j++)
                    {
                        for(int l = 0; l < 26; l++)
                        if(j == Plain_text[i])
                        {
                            Plain_text[i] = (l + k) % 26;
                            printf("%c", (char) Plain_text[i]);
                        }
                    }
                }
                else
                printf("%c", Plain_text[i]);
            }
    }
}

I cant seem to figure out what the problem is, any help woud be great.

1 Answer 1

2

On an argc != 2, you probably should tell the user what they did wrong before returning 1.

You don't need the

            if(Plain_text[i] == ' ')
            {
                printf("%c", Plain_text[i]);
            }
            else

as it's already included in your next if (space is not an alphabetic character).

You don't need inner for-loops, but you might want to differentiate between up- and lower-case plaintext, so inside the isalpha block, another if might be a good idea.

If Plain_text[i] is uppercase, it's in range 'A'-'Z', you could subtract 'A' to get a number of 0-25, then add k, take the remainder of division by 26 (%26), and then add 'A' again to shift it back into the range of 'A'-'Z'.

Lowercase would be same with 'a' instead of 'A'.

You must log in to answer this question.

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