I am modifying this simple qwerty cypher so it accepts a key of the users choosing, can I just add the string to replace the hard coded key or is there more to do?
I have tried using a string from a scanf user input. It does work when the is hard coded in place but I would like to be able to add it as a user.
The original code I am working off is:
char* ciphertext = "qwertyuiopasdfghjklzxcvbnm";
char input[500];
printf("Enter text: ");
fgets(input, sizeof(input), stdin);
input[strlen(input) - 1] = 0;
int count = strlen(input);
char output[count];
for(int i = 0; i < count; i++) {
int index = ((int) input[i]) - 97;
if(index < 0) {
output[i] = ' ';
}
else {
output[i] = ciphertext[index];
I replaced:
char* ciphertext = "qwertyuiopasdfghjklzxcvbnm";
with:
char KEY[26];
printf("Enter key text:");
fgets(KEY, sizeof(KEY), stdin);
As well as swapping ciphertext[index] for KEY[index] in the final line.
My code looks like:
char KEY[26];
printf("Enter key text:");
fgets(KEY, sizeof(KEY), stdin);
char input[999];
printf("Enter text: ");
fgets(input, sizeof(input), stdin);
input[strlen(input) - 1] = 0;
int count = strlen(input);
char output[count];
for(int i = 0; i < count; i++) {
int index = ((int) input[i]) - 97;
if(index < 0) {
output[i] = ' ';
}
else {
output[i] = KEY[index];
}
}
output[count] = 0;
printf("output: %s\n", output);
The code runs, allows and input for KEY but then skips allowing the user to add a text to encrypt and prints a letter as the encrypted message.
When I use the key: qwertyuiopasdfghjklzxcvbnm it prints d (13th input) when I use: qazwsxedcrfvtgbyhnujmikolp it prints y (16th input) When I use: qazxswedcvfrtgbnhyujmkiolp It prints n (again the 16th input)