Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flushall() doesn't work - in C

I have to get many chars one by one with getchar() function.

I have to clean the buffer after using the function, but flushall() doesn't do it. After the second iteration of the function it gets '\n' as input. I tried using fflush(), _flushall(), but no one succeed doing this. What is the reason for that? please help.

Note: I must use getchar().

int i;
char c;
for (i = 0; i < 5; i++)
{
    c = getchar();      
    printf("%c", c);
    _flushall();
}
like image 552
Asher Avatar asked Feb 28 '26 17:02

Asher


1 Answers

If you want to throw away junk in the input buffer, a good way to do it is

int c;
do c = getchar(); while (c != EOF && c != '\n');

This will discard up to and including the next newline or end-of-file, which is usually what you want.

If you are trying to write a program that responds to single keystrokes as the user presses each one, this won't work for you, but that's because the entire stdio.h interface won't work for you; you will need to use something else, such as ncurses or a GUI "widget" library.

like image 108
zwol Avatar answered Mar 02 '26 05:03

zwol