Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

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

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 gets() to get a string.

The problem is that fflush(stdin) doesn't do what is expected from it: The program continues skipping gets() and I can't write any phrase in the console to be read.

My code is the next one:

#include <string.h>
#include <stdio.h>

int main(){
    char nombre[10];
    char mensaje[80];

    printf("Type your name:
");
    scanf("%s", nombre);

    fflush(stdin);

    printf("Now, type a message:
");
    gets(mensaje);

    printf("3/%s:%s",nombre,mensaje);
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

This will work:

#include <string.h>
#include <stdio.h>

int main(){
    char nombre[10];
    char mensaje[80];
    int c;

    printf("Type your name:
");
    scanf("%9s", nombre);

    while((c= getchar()) != '
' && c != EOF)
            /* discard */ ;

    printf("Now, type a message:
");
    gets(mensaje);

    printf("%s:%s",nombre,mensaje);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...