In my program I have the user input a phrase, and I use the fgets function to retrieve it so it can count the spaces between words. The problem is my program skips over fgets and continues into the next scanf. Can someone explain what's the problem and how I can fix it?
#include<stdio.h>
#include<string.h>
int main(){
char plaintext[50], key[15];
char encrypt[50];
int EncryptOp = 1, DecryptOp = 2, choice;
printf("Enter 1 for Encryption or 2 For Decryption: ");
scanf("%d", &choice);
if(choice ==EncryptOp){
printf("Enter Plaintext for Encryption: ");
fgets(plaintext,50,stdin);
printf("Enter Keyword:");
scanf("%s", &key);
printf("Plaintext:%s\n Keyword:%s\n", plaintext, key);
}else if(choice ==DecryptOp){
printf("Enter Encrypted Message for Decryption: ");
scanf("%s", &encrypt);
}
return 0;
}
When I run it and choose 1 it outputs this:
Enter 1 for Encryption or 2 For Decryption: 1
Enter Plaintext for Encryption: Enter Keyword:
As you can see it doesn't allow the user to input the plaintext and goes right into asking them to enter a keyword.
Look here: https://stackoverflow.com/a/20156727/14273548
Copied answer to here because of miminum characters.
after this line scanf("%d",&e)
add a getchar()
like this :
scanf("%d",&e);
getchar();
when you press Enter the newline character stays in the buffer so when fgets is called the newline is passed to it and it actes as if you pressed Enter