How to clear the buffer in the C language?

In C language, the fflush function can be used to clear the buffer. The fflush function is used to refresh the buffered data in the stream and write it to the output device.

The specific grammar is as follows:

int fflush(FILE *stream);

Explanation of parameters:

  1. stream: pointer pointing to the stream to be refreshed. Typically, standard input stream stdin, standard output stream stdout, or standard error stream stderr can be used.

Example code:

#include <stdio.h>

int main() {
    printf("请输入任意字符:");
    fflush(stdout); // 刷新标准输出流缓冲区
    
    char ch = getchar();
    printf("您输入的字符是:%c\n", ch);
    
    return 0;
}

In the above example, by using fflush(stdout) to flush the buffer of the standard output stream, ensuring that the output prompt text is immediately displayed before using the getchar function to read input.

bannerAds