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)
");
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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…