tommy
tommy

Reputation: 13

Caesar encryption not returning wanted value

I am solving pset2s caesar and I've been encountering some bugs and I also couldn't figure out how to check if the given key was an integer or not but I'm guessing its with some type of error control? Anyways this is what I've written so far:

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

char rotate(char c, int n);

char lower[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char upper[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

int main(int argc, string argv[])
{
    if (argc != 2){
        printf("Usage: ./caesar key\n");
        return 1;
    }
    int key = atoi(argv[1]);
    string word = get_string("plaintext: ");
    for(int i = 0; i < strlen(word); i++){
        word[i] = rotate(word[i], key);
    }
    printf("ciphertext: %s\n", word);
}

char rotate(char c, int key){
    int location;
    if(isupper(c)){
        location = c - 'A';
        location = location + key % 26;
        c = upper[location];
    }
    else if(islower(c)){
        location = c - 'a';
        location = location + key % 26;
        c = lower[location];
    }
    return c;
}

Upvotes: 0

Views: 49

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311028

This code snippet

int location;
if(isupper(c)){
    location = c - 'A';
    location = location + key % 26;
    c = upper[location];
}
else if(islower(c)){
    location = c - 'a';
    location = location + key % 26;
    c = lower[location];
}

is invalid. It seems you mean

c = 'A' + ( location + key ) % 26;

and

c = 'a' + ( location + key ) % 26;

or

c = upper[ ( location + key ) % 26];

and

c = lower[( location + key ) % 26];

And these statements

    c = upper[location];
    c = lower[location];

must be removed.

Also it will be more safer to write

if(isupper(( unsigned char )c)){

and

if(islower(( unsigned char )c)){

To determine whether the key is specified correctly use the function strtol instead of atoi.

Upvotes: 1

Related Questions