How to remove extra characters input from fgets in

2019-05-19 08:25发布

I heard using gets() is bad in C programming and it's safer using fgets... So I am using fgets. However, I encounter a problem with fgets: I entered too much characters and somehow, it overflows.

How to get rid of the extra input characters?

char answer[4];
char answer2[4];

fgets(answer,sizeof(answer),stdin);
printf("answer: %s\n",answer);

fgets(answer2,sizeof(answer2),stdin);
printf("answer2: %s\n",answer2);

For example, for the first fgets, I enter 123456, the output I get is

answer: 123
answer2: 456

How do I remove the 456 from going into the next fgets input? I want the output like this after entering 123456 for the 1st fgets:

answer: 123

Then, user continue to enter an input for the next fgets...

2条回答
神经病院院长
2楼-- · 2019-05-19 08:36
fgets(answer,sizeof(answer),stdin);
printf("answer: %s\n",answer);
if(!strchr(answer, '\n'))     //newline does not exist
    while(fgetc(stdin)!='\n');//discard until newline
fgets(answer2,sizeof(answer2),stdin);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-19 08:36

You might also be interested in getline().

#include <stdio.h>

int main()
{
        char *inpt;
        size_t len = 1024;
        size_t n;

        n = getline(&inpt, &len, stdin);
        inpt[n - 1] = '\0';

        printf("%s", inpt);
        return 0;

}

I also sometimes like to use a small modified version of getline() which I write myself. This one discards the trailing newline completely.

#include <stdio.h>

size_t mygetline(char *, size_t);

int main()
{
        char inpt[1024];

        mygetline(inpt, 1024);
        printf("%s", inpt);
        return 0;

}

size_t mygetline(char *s, size_t lim)
{
        int c;
        size_t i;
        for ( i = 0 ; i < lim-1 && (c=getchar()) != '\n' ; ++i )
                s[i] = c;
        s[i] = '\0';
        return i;
}
查看更多
登录 后发表回答