Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top