Monday 15 June 2015

c - Substitution Cipher - issues modifying strings -



c - Substitution Cipher - issues modifying strings -

the next code broken when trying run due issue replacing character on line 33. replacing character in string incorrectly?

the code designed encrypt lowercase characters in *cat string. each character in code2 'mapped' character in same position in code1. lowercase chars in *cat replaced substituted char code2.

//ben adamson //v1.0 #include <stdio.h> #include <conio.h> #include <string.h> #include <ctype.h> void code(char *s); int main() { char *cat = "the cat sat"; code(cat); _getch(); homecoming 0; } void code(char *s) { char code1[] = "abcdefghijklmnopqrstuvwxyz"; char code2[] = "bpduhijkaltxwmrzfoysvngeqc"; char *letter; unsigned int i, letterpos; for(i=0; i<strlen(s); i++) { if(isalpha(s[i]) && islower(s[i])) { letter = strchr(code1, s[i]); letterpos = (int)(letter - code1); s[i] = code2[letterpos]; } } printf("new string %s", s); }

char *cat = "the cat sat";

her cat read only.

s[i] = code2[letterpos];

you need allocate memory if need write it.

char *cat = malloc(100);

better way is:

char *cat = strdup("the cat sat");

c string encryption

No comments:

Post a Comment