I was writing some code and used fgets to get user input. And then i wrote a loop over my code to keep asking for user input until the user prints quit. But the second time it asked, it wrote "Please enter your input" 2 times instead of 1 , and didn't wait for my input the first time. So, i googled it and found that the stdin buffer was filled and it had to be cleared. I found this solution :
void dump_line(FILE * fp) {
int ch;
while ((ch = fgetc(fp)) != EOF && ch != '\n') {
/* null body */;
}
}
and then calling from the main function :
dump_line(stdin);
I have a very hard time understanding it. As i understand it, it simply assigns "ch" the value of fgetc(stdin) .. I simply cant understand how would assigning fgetc(stdin) to "ch" clear the buffer . Thank you very much for your help!
Here is an old snippet I am using for user input if I really need to do it in pure C:
int get_line(char *buffer, int bsize)
{
int ch, len;
fgets(buffer, bsize, stdin);
/* remove unwanted characters from the buffer */
buffer[strcspn(buffer, "\r\n")] = '\0';
len = strlen(buffer);
/* clean input buffer if needed */
if(len == bsize - 1)
while ((ch = getchar()) != '\n' && ch != EOF);
return len;
}
It retrieves bsize
amount of letters from stdin and stores them into given buffer. stuff left in stdin input buffer will be cleaned automatically. It also removes newlines (\r and \n) from the input data.
Function returns the amount of characters sucessfully read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With