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

前端 未结 3 811
爱一瞬间的悲伤
爱一瞬间的悲伤 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:45

    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 
    

提交回复
热议问题