fflush stdin(C语言 fflush(stdin)是什么意思)

本文目录
C语言 fflush(stdin)是什么意思
fflush(stdin)中stdin是标准输入的意思。
fflush(stdin)的作用是清空标准输入缓冲区。
举例说明如下:
int a;
char c;
scanf(“%d“,&a);
fflush(stdin); // 清空输入缓冲区
scanf(“%c“,&c);如果不加fflush(stdin)的话,第一次输入的回车可能会被第二次输入操作所捕捉,也即变量c的值将会是回车符,并不会接收用户输入的字符。
C语言fflush(stdin)函数是什么意思,在什么情况下用它
1、fflush(stdin)是清空输入缓冲区的意思。stdin就是标准输入 std即standard(标准),in即input(输入),合起来就是标准输入。 一般就是指键盘输入到缓冲区里的东西。
2、在清除文件缓冲区时使用,文件以写方式打开时将缓冲区内容写入文件。
例:
#include 《conio.h》
#include 《io.h》
#include 《stdio.h》
#include 《string.h》
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg = “This is a test“;
/* create a file */
stream = fopen(“DUMMY.FIL“, “w“);
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf(“Press any key to flush DUMMY.FIL:“);
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf(“\nFile was flushed, Press any key to quit:“);
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream’s internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
扩展资料
使用fflush的注意事项
1、MSDN 文档里也清楚地写着:fflush on input stream is an extension to the C standard (fflush 操作输入流是对C标准的扩充)。以下是 C99 对 fflush 函数的定义:int fflush(FILE *stream);
2、如果stream指向输出流或者更新流(update stream),并且这个更新流最近执行的操作不是输入,那么fflush函数将把任何未被写入的数据写入stream指向的文件(如标准输出文件stdout)。
3、fflush函数的行为是不确定的。fflush(NULL)清空所有输出流和上面提到的更新流。如果发生写错误,flush函数会给那些流打上错误标记,并且返回EOF,否则返回0。
4、如果 stream 指向输入流(如 stdin),那么 fflush 函数的行为是不确定的。故而使用 fflush(stdin) 是不正确的。
参考资料来源:百度百科—fflush(stdin)

更多文章:
majority of(the majority of 和 a majority of的区别以及用法例句)
2026年10月11日 07:40
another time(another time和other time的区别)
2026年10月11日 05:00







