简体   繁体   中英

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();
}

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.

I implemented an intelligent solution to clear the input buffer. This solution has 3 advantages:

  1. It does not block if there is nothing in the input buffer.

  2. In case there are characters in the input buffer it clears them and does not wait to press Enter.

  3. The characters that are in the input buffer (as a result of the user clicking on the keyboard) will not be displayed on the screen.

Here is my solution

#include <conio.h>
#include <Windows.h>

void my_flushall()
{
    while (_kbhit())_getch(); // flushall
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM