문제

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

도움이 되었습니까?

해결책 2

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top