Code:
#include <stdio.h>
int main(void)
{
int ch;
char buf[BUFSIZ];
puts("Flushing input");
while ((ch = getchar()) != '\n' && ch != EOF);
printf ("Enter some text: ");
if (fgets(buf, sizeof(buf), stdin))
{
printf ("You entered: %s", buf);
}
return 0;
}
stdin is a standard FILE* variable that points to the input stream normally used for keyboard input. The fflush() function is deemed to flush buffers. Put the two together and you have a method for clearing the input stream easily, right? WRONG!
Alright I see the code and since I didnt find anything else might as well try to work backwards instead of assuming I know it and understand and leave it at that.
Sorry for what seems like a pointless question but still Id rather look like an ass and learn it than screw it up later.
From what I see it looks like the while loop I think would amount to:
Code:
while ((ch = getchar()) != '\n' && ch != EOF);
{
printf ("Enter some text: ");
if (fgets(buf, sizeof(buf), stdin))
{
printf ("You entered: %s", buf);
}
}
and contains all of those statements. I don't really get the ch = getchar() but it looks like that is used to assign any character into ch for testing.
printf prompts the user to enter some text which goes to the buffer.
then if(fgets(buf,sizeof(buf),stdin)) is testing for a clear buffer and if it doesn't find one it reads it into buf. Then if this input is clean it the buffer is clear if it isn't and fgets doesnt see the null or newline it appends a newline character and the buffer is cleared correctly. Is this close to correct?