CS50 Caesar - ASCII letters and Output format

573 Views Asked by At

I've been trying to work through the less comfortable version of cs50's Caesar problem, and would just like to preface this question by saying I'm a complete beginner.

The program is supposed to ask the user to input a key and plaintext, and then cipher that text using the provided key. For example, for a key of 2, "aba" would be "cdc".

I think I managed to get the program running correctly, apart from two things: the output for the ciphertext or encrypted text should be in the form of "Ciphertext: " instead of just the strings outputted, as my program does. The other, more significant problem, is if the inputted key is larger than 26, where the output includes other unwanted symbols instead of just letters.

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

int main (int argc, string argv [])
{
    if (argc != 2)
    {
        printf ("Error. Instructions not followed.\n");
        return 1;
    }
    int key = atoi(argv [1]);
    printf ("%i\n", key);
    printf("Plaintext:");
    string plaintext = get_string();
    int i = 0;
    for (char c = 'A'; c <= 'Z'; c++)
    {
        i++;
    }
    for (int j = 0; j < strlen(plaintext); j++)
    {
        char ciphertext = ((plaintext[j]+key%26));
        if (isupper (plaintext[j]) || islower (plaintext[j]))
        {
            printf("%c", ciphertext);
        }
        if (isalpha (plaintext [j]) == false)
        {
            printf("%c", (plaintext[j]));
        }
    }

printf("\n");
}

Any help would be much appreciated. Thank you.

1

There are 1 best solutions below

0
On

First of all, you have to follow the specifications of the problem. That is, you have to print out the word 'plaintext:' before taking input and print out 'ciphertext:' before giving any output. As the checking process is automated, this becomes very important. Notice the case of those words in your problem statement. Secondly, I will let you figure out the logic by yourself, which is the important part of the problem set. Try watching the next few lectures and learn how to use the debugger in the CS50 IDE. It will help you a lot to solve problems in your code on your own.