Search code examples
clinuxfgets

fgets not working in C linux


I always feel lots of problem while taking char or string inputs in C linux. And see this prog. It's not taking input from the user. Please help.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char *buf;
    int msglen;
    printf("\nEnter message length\t");
    scanf("%d",&msglen);       

    buf=malloc(msglen);

    //memset(buf,'\0',msglen+1);
    printf("\nEnter data\t");
    fflush(stdin);
    fgets(buf,msglen,stdin); //NOT WORKING

    fputs(buf,stdout);
    return 0;
}   

Thanks :)


Solution

  • Use getchar() instead of fflush(), it works.