• Uncategorized

About c : Caesar-cipher-program-written-in-C-has-a-bug

Question Detail

I wrote a program for cs50 that’s supposed to take in a (integer)’key’ (at run-time) and output a prompt for ‘plaintext’ which will then output an encrypted version of the plaintext according to the caesar cipher function.
The program when I run it in the cs50 IDE compiles in the terminal (‘make caesar’) and when I input the ‘key’ at run-time (e.g. ./caesar 2) and I get the prompt[Plaintext: ] and for instance I put “Hello”. The output would be [Ciphertext: 74HelloHelloHelloHello74HelloHelloHelloHello74HelloHelloHelloHello74HelloHelloHelloHello74HelloHelloHelloHello] instead of the expected [Ciphertext: JGOOQ].


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

// Get the 'key' value at run-time (./ceasar 'key').
// key_value must be a digit/number).
// String argv[1] must be converted to int.
// Prompt user for plaintext.
// plaintext must be converted by casaer cipher to ciphertext.
// Print ciphertext.

// Declaring variables.
string plaintext;
string ciphertext;
int key_value;

// declaring the caesar cipher function (takes in an array of characters (aka string) and an 
void caesar_cipher(char str[], int shift_value);

int main(int argc, string argv[])
    // check if there are two arguments at run-time and the second argument (argv[1]) is a 
    if (argc == 2 && isdigit(*argv[1]))
        // convert string argv[s] to an int.
        key_value = atoi(argv[1]);
        // Prompt user for plaintext.
        plaintext = get_string("Plaintext: ");

        printf("Ciphertext: ");

        // iterate through plaintext letter-by-letter
        for (int i = 0, n = strlen(plaintext); i < n; i++)
            caesar_cipher(plaintext, key_value);
        return 0;
        printf("Usage: ./caesar 'key'\n");
        return 1;
// char str[] will take in 'plaintext' and int shift_value will take in 'key'
void caesar_cipher(char str[], int shift_value)
    int i = 0;

    while (str[i] != '\0')
        // case for uppercase letters
        if (str[i] >= 'A' && str[i] <= 'Z')
            printf("%i", (((plaintext[i] - 'a') + shift_value) % 26) + 'a');
         // case for lowercase letters
        else if (str[i] >= 'a' && str[i] <= 'a')
            printf("%i", (((plaintext[i] - 'A') + shift_value) % 26) + 'A');
            printf("%s", str);
        //increment after every character

Question Answer

No answer for now.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.