-3

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • Does this answer your question? [fgets instructions gets skipped.Why?](https://stackoverflow.com/questions/2907062/fgets-instructions-gets-skipped-why) – Random Davis Sep 28 '20 at 17:47
  • Also if you stepped through your code line-by-line with a debugger, you'd clearly see nothing's getting "skipped". You should really have debugged this before posting here. – Random Davis Sep 28 '20 at 17:47
  • Always check the return value of fgets, scanf etc., and fail on any error. – pts Sep 28 '20 at 18:00
  • Never use `gets`! How is this comment relevant here? Because `scanf("%s")` has precisely the same problem. Never use `"%s"` in scanf. Always use `scanf("%14s")` (or the appropriate size). – William Pursell Sep 28 '20 at 18:07
  • `scanf("%s")` will stop when faced with space, `fgets` does not, it's not always correct to use `scanf`. – Uriya Harpeness Sep 28 '20 at 18:13

2 Answers2

1

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

Uriya Harpeness
  • 628
  • 1
  • 6
  • 21
0

scanf() reads exactly what you asked it to, leaving the following \n from the end of that line in the buffer where fgets() will read it. I would recommend using fgets() for reading input too and using sscanf() to read choice integer:

    char input[10];

    ...
    fgets(input, 10, stdin);
    sscanf(input, "%d", &choice);
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40