Matthew Dickson
Matthew Dickson

Reputation: 1

Why does my caesar solution for CS50 Problem Set 2 sometimes throw out random characters

I am working on Problem Set 2 on CS50 doing the caesar question and having some trouble.

I have tried the below code but it seems to only produce random characters for single character plaintext entries and world, say hello!

Please excuse the lack of comments.

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

//expects function to be declared later
bool validate(string key);
//Command line argument that launches with KEY
int main(int argc, string argv[])
{
//reject all input that is not a single string with the key
    string key = argv[1];
    if (argc != 2)
        {
        printf("Usage: ./caesar key");
        return 1;
        }
    else if (validate(key)==true)
    {
        string plaintext = get_string("plaintext: ");
        char ciphertext[strlen(plaintext)];
        int intkey = atoi(key);

        for(int i = 0; i < strlen(plaintext); i++)
        {
            if ((plaintext[i] >= 65 && plaintext[i] <=90) || (plaintext[i] >=97 && plaintext[i] <=122))
            {
                if ((plaintext[i]+(intkey % 26) > 122) || (plaintext[i]+(intkey % 26) >90 && plaintext[i]+(intkey % 26) < 97))
                {
                    ciphertext[i] = plaintext [i] - (26 - intkey % 26);
                }
                else
                {
                    ciphertext[i] = plaintext[i] + intkey % 26;
                }
            }
            else
            {
                ciphertext[i] = plaintext[i];

            }

        }

        printf("ciphertext: %s\n", ciphertext);
    }
    else
    {
        printf("Usage: ./caesar key");
    }

}

bool validate(string key)
{
    int count = 0;
    for (int i = 0; i < strlen(key); i++)
    {
        if(isdigit(key[i]))
        {
            count++;
        }
    }
    if (count == strlen(key))
    {
        return true;
    }
    else
    {
        return 1;
    }
}

I am working on Problem Set 2 on CS50 doing the caesar question and having some trouble.

I have tried the below code but it seems to only produce random characters for single character plaintext entries and world, say hello!

Please excuse the lack of comments.

Upvotes: 0

Views: 333

Answers (1)

Armali
Armali

Reputation: 19395

ciphertext[] is not terminated with a null character, it even lacks the room for it, hence printf("ciphertext: %s\n", ciphertext) may well produce random characters after the actual ciphertext. This may be rectified by adding 1 to both occurrences of strlen(plaintext).

Upvotes: 1

Related Questions