Douglas de Moura
Douglas de Moura

Reputation: 187

Why I am getting an empty value in this implementation of Caesar's cipher?

I've implemented the Caesar's cipher in C, and, despite the algorithm is working, I didn't understood why (sometimes) I get an empty value if I do not subtract the first letter of the alphabet before adding the key. Here's the full code (see line 59 or search for return (letter + k) % 26):

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

string caesar_cipher(string text, int k);
char replace_letter(char letter, int k);
bool is_numeric(string input);

int main(int argc, string argv[])
{
    if (argc != 2 || (argc == 2 && !is_numeric(argv[1])))
    {
        fprintf(stderr, "You must specify a key to the cipher! Exiting...\n");
        exit(EXIT_FAILURE);
    }

    // Convert command line argument to integer.
    int k = atoi(argv[1]);

    // Prompts user for the text to encrypt
    string text = get_string("plaintext: ");

    // Returns encrypted text
    printf("ciphertext: %s\n", caesar_cipher(text, k));

    exit(EXIT_SUCCESS);
}

string caesar_cipher(string text, int k)
{
    int text_length = strlen(text);
    string ciphered_text = text;

    for (int i = 0; text[i] != '\0'; i++)
    {
        ciphered_text[i] = replace_letter(text[i], k);
    }

    return ciphered_text;
}

char replace_letter(char letter, int k)
{
    // Early return when 'letter' is a non-alphabetical character
    if (!isalpha(letter))
    {
        return letter;
    }

    char operation_letter = 'a';

    if (isupper(letter))
    {
        operation_letter = 'A';
    }

    // return (letter + k) % 26; // Sometimes, returns an empty value
    return ((letter - operation_letter + k) % 26) + operation_letter;
}

// Loop over characters to check if each one of them is numeric
bool is_numeric(string input)
{
    for (int i = 0; input[i] != '\0'; i++)
    {
        // If character is not numeric
        // returns false.
        if (isdigit(input[i]) == 0)
        {
            return false;
        }
    }

    return true;
}

Can anybody explain why this happens?

Upvotes: 0

Views: 57

Answers (1)

high-rolls
high-rolls

Reputation: 131

You need to account for the first letter of the alphabet (either a or A) in your functions because chars are internally represented as an integer number (usually only a single byte, but it depends on the encoding). In ASCII for example, doing a % 26 will result in any of the 26 first values of the ASCII table, none of which are actual letters. Hopefully I made myself clear.

Upvotes: 1

Related Questions