int prompt(const char *output_message, char *input, const int MAX_SIZE)
{
printf("%s", output_message);
int i = 0;
char ch = '\0';
while (1)
{
ch = (char)getchar();
if (ch == '\n' || ch == EOF)
{
break;
}
else if (i < (MAX_SIZE - 1))
{
input[i ] = ch;
}
}
input[i] = '\0';
return i;
}
I wrote this function to get an input string input from the user. So getchar(), is going through the buffer until it reaches a newline or the end of the file. My question is does flushing the input buffer mean to move the FILE pointer(or whatever implementation is there) away from the currently written part in the buffer like I'm doing with getchar()? What does it actually mean to "flush the input buffer"?
CodePudding user response:
"Flushing the input buffer" refers to the attempt to discard unwanted characters from the input stream so that they do not perturb later input calls.
In your code, it doesn't look like you'll have this problem, so flushing the input buffer should not be an issue for you.
The unwanted input issue typically occurs when you're doing input using scanf
. scanf
typically leaves the user's newline on the input buffer, but later calls to getchar
or fgets
(or even scanf
) can be badly confused by this.
The problem with flushing the input is that there isn't really a good way of doing it. A popular although not recommended technique is to call fflush(stdin)
. That looks like it ought to be just the ticket, but the problem is that it's not well-defined and not guaranteed to work (although some programmers have found that it works well enough for them, on some platforms).
See this question and this question (maybe also this one) for much more on this issue.