Calling scanf() after another string input functio

2019-02-28 13:30发布

问题:

Here's a small program:

#include <stdio.h>

int main() {
  char str[21], choice[21]; int size;
  while(1){
    printf("$ ");
    fgets(str, 20, stdin);
    printf("Entered string: %s", str);
    if(str[0] == 'q') {
      printf("You sure? (y/n) ");
      scanf("%s", choice);
      if(choice[0] == 'y' || choice[0] == 'Y')
        break;
    }
  }
  return 0;
}

It reads a string using fgets(). If the string starts with a q, it confirms if the user wants to quit, and exits if the user types y.

When I run it and type q, this happens:

$ q
Entered string: q
You sure? (y/n) n
$ Entered string: 
$ 

Note the $ Entered string:. Clearly, fgets() got an empty character or something as input, even though I didn't type anything.

What's going on?

回答1:

As described in other answer scanf call leaves the newline in the input buffer you can also use getchar() after scanf like this :

scanf("%20s", choice);// always remember( & good) to include field width 
                      // in scanf while reading

Strings otherwise it will overwrite buffer in case of large strings `

getchar();  //this will eat up the newline 

Besides , you should also use fgets like this :

fgets(str,sizeof str, stdin); //Its better 


回答2:

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.



回答3:

Use a 'char' of a specific size char choice [1]

OR

char c[1];
c = getchar();
if(c[0] == 'y' || c[1] == 'y'){
 // DO SOMETHING
}


标签: c scanf