C program skips fgets [duplicate]

倾然丶 夕夏残阳落幕 提交于 2021-01-28 06:28:45

问题


My program compiles ok but it when it calls the getinput() function it never prompts for input.

Edited to show more code, I added fflush but it still skips it for some reason.

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


main(){

    char mystring[] = "It's equal to it. ";
    int k = 32;
    int e;
    printf("Enter a number: ");
    scanf("%d",&e);
    if(e == k){
        printf("\n\n%s\n",mystring);

    } else if(e < k){
        printf("\n\n%d\n",e);

    } else {


        getinput();
    }

    exit(0);

}

int getinput(){

    char gettext[64];

    printf("Enter text here: ");
    fflush(stdout);
    fgets(gettext, 64, stdin);
    printf("\n\nYou entered: %s\n\n",gettext);
    return 0;


}

回答1:


after this line scanf("%d",&e) add a getchar() like this :

scanf("%d",&e);
getchar();

when you press Enter the newline character stays in the buffer so when fgets is called the newline is passed to it and it actes as if you pressed Enter




回答2:


Try calling fflush(stdout); after your first printf.

printf will flush it for you, but only when it has a newline at the end (e.g. printf("hi\n");)



来源:https://stackoverflow.com/questions/20150845/c-program-skips-fgets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!