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!