Fabio Operti Fabio Operti - 3 months ago 7
C Question

Got stuck with Caesar.c

I am trying to run the program assignment caesar.c from the edx Introduction to programming. It requires a program able to encrypt a string with the Caesar encryption: therefore, the user has to enter a key (command-line); for example with a key of 2 a 'A' character needs to be encrypted in a 'C' character; the problem starts when you have to enter a key greater than 26, which is the number of alphabetical letters. For a key of 27 and an 'A' character for example, the program must return 'B' like a key of 1.

I have tried to transform the ASCII values of the characters to alphabetical values from 0 to 26 in order to use the modulus operator when the key is equal or greater than 26.
It returns me a segmentation fault. Can anyone help me with some suggestions of the causes of my error?

Here's the program:

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

int key;

// function for an alphabetic value with non capital letters

int alpha_low( char c )
{
int alpha_value;
alpha_value = (int) c - 97;
return alpha_value + ( key % 26 );
}

// function to return to ascii valuee for non capital letters

char ascii_low( char c )
{
return (char) alpha_low( c ) + 97;
}

// function for an alphabetic value with capital letters

int alpha_up( char c )
{
int alpha_value;
alpha_value = (int) c - 65;
return alpha_value + ( key % 26 );
}

// function to return to ascii value for capital letters

char ascii_up( char c )
{
return (char) alpha_up( c ) + 65;
}


int main(int argc, string argv[])
{
int result;
string p;
key = atoi( argv[1] );

if( argc != 2 || key < 0 )
{
printf("Usage: ./caesar key(positive integer)\n");
return 1;
}

printf("Please, write a plaintext: ");
p = GetString();

for( int i = 0, n = strlen(p); i < n; i++)
{
if ( isalpha(p[i]) )
{
if ( islower(p[i]) )
{
result = alpha_low( p[i] );
printf("%c", ascii_low( p[i] ));
}
else if( islower( p[i]) )
{
result = alpha_up( p[i] );
printf("%c", ascii_up( p[i]) );
}
}
}

return 0;
}

Answer

A function to caesar an alphabetic char should be like (decomposed in elementary steps):

int caesar_lower(int c,int key) {
    int v = c-'a'; // translate 'a'--'z' to 0--25
    v = v+key;     // translate 0--25 to key--key+25
    v = v%26;      // translate key--key+25 to key--25,0--key-1
    v = v+'a';     // translate back 0--25 to 'a'--'z'
    return v;
}