Calling scanf() after another string input function creates phantom input

前端 未结 3 842
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-25 11:00

Here\'s a small program:

#include 

int main() {
  char str[21], choice[21]; int size;
  while(1){
    printf(\"$ \");
    fgets(str, 20, stdin);
         


        
3条回答
  •  悲哀的现实
    2021-01-25 11:49

    It because the scanf call reads a character, but leaves the newline in the buffer. So when you next time call fgets is finds that one newline character and reads it resulting in an empty line being read.

    The solution is deceptively simple: Put a space after the format in the scanf call:

    scanf("%s ", choice);
    /*       ^    */
    /*       |    */
    /* Note space */
    

    This will cause scanf to read and discard all training whitespace, including newlines.

提交回复
热议问题