Program doesn't execute gets() after scanf(), even using fflush(stdin)

后端 未结 5 1559
不思量自难忘°
不思量自难忘° 2020-12-01 22:54

After wasting too much time searching why my program doesn\'t execute gets() after using scanf(), I found a solution which is to use fflush(stdin) after scanf() to enable ge

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 23:39

    If flushing std doesn't work, then try reading in the extra characters and discarding, as suggested here.

    This will work:

    #include 
    #include 
    
    int main(){
        char nombre[10];
        char mensaje[80];
        int c;
    
        printf("Type your name:\n");
        scanf("%9s", nombre);
    
        while((c= getchar()) != '\n' && c != EOF)
                /* discard */ ;
    
        printf("Now, type a message:\n");
        gets(mensaje);
    
        printf("%s:%s",nombre,mensaje);
        return 0;
    }
    

提交回复
热议问题