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);}
}
}
@ddisec I have noted 3 mistakes
in your code .
First your scanf(" %c", message);
.Here you have to use %s
(String).
Second the result printing statements should be outside for-loop
.
Third putting if(ms >= 'a' && ms <= 'z'&& choice == 2)
inside if (ms >= 'a' && ms <= 'z' && choice == 1)
dose not make any sense.
Try this corrected code:-
#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);
getchar(); // to handle unwanted newline.
printf("Enter a message to process: ");
scanf("%49[^\n]", message);
printf(" \nEnter key:");
scanf("%d", &key);
for (i = 0; message[i] != '\0'; ++i)
{
ms = message[i];
if (ms >= 'a' && ms <= 'z' && choice == 1)
{
ms = ms + key;
}
else if (ms >= 'a' && ms <= 'z' && choice == 2)
{
ms = ms - key;
}
else if (ms > 'z')
{
ms = ms - 'z' + 'a' - 1;
}
else if (ms >= 'A' && ms <= 'Z' && choice == 1)
{
ms = ms + key;
}
else if (ms >= 'A' && ms <= 'Z' && choice == 2)
{
ms = ms - key;
}
else if (ms > 'Z')
{
ms = ms - 'Z' + 'A' - 1;
}
message[i] = ms; // Only single modification code needed.
}
if (choice == 1)
{
printf(" \nEncrypted message: %s", message);
}
else if (choice == 2)
{
printf(" \nDecrypted message: %s", message);
}
}