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...
You might also be interested in getline().
I also sometimes like to use a small modified version of getline() which I write myself. This one discards the trailing newline completely.