user3436838
user3436838

Reputation: 113

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 :)

Upvotes: 0

Views: 3806

Answers (3)

M.M
M.M

Reputation: 141648

When you read the integer with scanf("%d"....), it does not remove the newline from the input stream. So when you call fgets later, it reads and finds a newline , i.e. you read a blank line.

To read the next line instead you will need to consume that newline, e.g. getchar() as someone else suggested.

This sort of issue is common when you mix formatted I/O (scanf) with unformatted I/O.

Upvotes: 1

Ankit Kumar
Ankit Kumar

Reputation: 1463

fflush() is used to flush the output streams and not clear the remaining characters from stdin. use gets() or getchar() first to remove the EOF from stdin

Upvotes: 2

skrtbhtngr
skrtbhtngr

Reputation: 2251

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

Upvotes: 1

Related Questions