encryption - Got stuck with Caesar.c -
i trying run program assignment caesar.c edx introduction programming. requires program able encrypt string caesar encryption: therefore, user has enter key (command-line); example key of 2 'a' character needs encrypted in 'c' character; problem starts when have enter key greater 26, number of alphabetical letters. key of 27 , 'a' character example, program must return 'b' key of 1.
i have tried transform ascii values of characters alphabetical values 0 26 in order use modulus operator when key equal or greater 26. returns me segmentation fault. can me suggestions of causes of error?
here's program:
#include <stdio.h> #include <cs50.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int key; // function alphabetic value non capital letters int alpha_low( char c ) { int alpha_value; alpha_value = (int) c - 97; return alpha_value + ( key % 26 ); } // function return ascii valuee non capital letters char ascii_low( char c ) { return (char) alpha_low( c ) + 97; } // function alphabetic value capital letters int alpha_up( char c ) { int alpha_value; alpha_value = (int) c - 65; return alpha_value + ( key % 26 ); } // function return ascii value 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 plaintext: "); p = getstring(); for( int = 0, n = strlen(p); < 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; }
a function caesar alphabetic char should (decomposed in elementary steps):
int caesar_lower(int c,int key) { int v = c-'a'; // translate 'a'--'z' 0--25 v = v+key; // translate 0--25 key--key+25 v = v%26; // translate key--key+25 key--25,0--key-1 v = v+'a'; // translate 0--25 'a'--'z' return v; }
Comments
Post a Comment