My program below conducts a Caesar's cipher in C. For some reason, after a message has been input by the user, the printf(" \nEnter key:")
and
scanf("%d", &key)
statements get "jumped" over. My thought was something related to the input buffer having a char and newline entered causing the jump (hence the fflush
attempt). How do I prevent this behavior?
#include <stdio.h>
#include <stdlib.h>
int main() {
char message[50], ms;
int i, key, choice;
printf("Enter 1. to Encrypt, or 2. to Decrypt: ");
scanf(" %d", &choice);
printf("Enter a message to process: ");
scanf(" %c", message);
printf(" \nEnter key:");
fflush(stdin);
scanf("%d", &key);
for (i = 0; message[i] != '\0'; ++i) {
ms = message[i];
if (ms >= 'a' && ms <= 'z' && choice == 1) {
ms = ms + key;
if (ms >= 'a' && ms <= 'z' && choice == 2) {
ms = ms - key;
if (ms > 'z') {
ms = ms - 'z' + 'a' - 1;
}
}
message[i] = ms;
} else
if (ms >= 'A' && ms <= 'Z' && choice == 1) {
ms = ms + key;
if (ms >= 'A' && ms <= 'Z' && choice == 2) {
ms = ms - key;
}
if (ms > 'Z') {
ms = ms - 'Z' + 'A' - 1;
}
message[i] = ms;
}
if (choice == 1) {
printf(" \nEncrypted message: %s", message);}
else if (choice == 2) {
printf(" \nDecrypted message: %s", message);}
}
}