2

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...

Lord Rixuel
  • 1,173
  • 6
  • 24
  • 43

2 Answers2

6
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);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • Thank you very much! It wasn't easy researching an answer like yours on the net. Thank you again :) I like it. It's short and simplier to understand. – Lord Rixuel May 22 '15 at 04:12
  • Nice implementation. Question: how does it work when I issue a `CTRL+D` sequence instead of hitting `ENTER` at the end of an input sequence? It's to my understanding that there should be no newline character in the input sequence if the input is `This is a test ^D^D`, yet this code still works as if I just hit `ENTER` at the end. – Cloud May 24 '17 at 17:09
2

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;
}