c - fflush() 函数不适用于标准输入

标签 c stdin fflush

我很抱歉这个愚蠢的问题。我有 C 程序提示用户输入年龄和姓名 然后将年龄和姓名打印到屏幕上。这是我从书上读到的练习。

这个程序:

#include <stdio.h>

int main (void) {
   int age;
   char name[20];

   puts("Enter your age:");
   scanf("%d",&age);

   fflush(stdin);

   puts("Enter your name:");
   scanf("%s",name);

   printf("Your age is %d\n",age);
   printf("Your name is %s\n",name);

   return 0;
}

当我向第一个 scanf() 输入额外字符时,程序终止并将额外字符分配给下一个 scanf()

然后我更改了代码,添加了名为 clear_buff() 的函数,并在 clear_buff() 中使用了 fgets 函数来读取流中的剩余字符。代码按我预期的方式工作。

#include <stdio.h>

#define MAXLEN 80

void clear_buff(void);

int main (void) {
  int age;
  char name[20];

  puts("Enter your age:");
  scanf("%d",&age);

  clear_buff();

  puts("Enter your name:");
  scanf("%s",name);

  printf("Your age is %d\n",age);
  printf("Your name is %s\n",name);

  return 0;
}

void clear_buff(void){
   char junk[20];
   fgets(junk,MAXLEN,stdin);
}

我的问题是为什么 fflush(stdin) 不能在这个程序中工作?

书上说 fflush 函数清除流上的所有缓冲数据。我知道 fflush() 函数是处理 I/O 流时的 C 标准函数。

最佳答案

fflush 旨在处理输出或更新流,将其与输入流一起使用是未定义的行为,来自 fflush 的 cppreference C 部分:

The behavior is undefined if the given stream is of the input type or if the given stream is of the update type, but the last I/O operation was not an output operation.

undefined behavior是标准未指定的行为,这意味着您的程序的结果是不可预测的,这可能意味着看似正常的行为或崩溃或其他不良影响。

cppreference 与草案 C99 标准部分 7.19.5.2 中的语言一致 fflush 函数 说:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

虽然这不是您真正的问题,而且您似乎已经找到了解决方法,但问题 C, flushing stdin涵盖了刷新 stdin 的一些正确方法。

关于c - fflush() 函数不适用于标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26446297/

相关文章:

c - while ( *(mychar++)) 什么时候停止

c - 如何使用C制作帕斯卡三角形

将 unsigned char * (uint8_t *) 转换为 const char *

python - python子进程的自定义标准输入

Golang os.stdin 作为 Goroutines 中的阅读器

c - 使用 fwrite() 将标准输入写入文件

c - 试图计算 Pi

c - fflush(stdin) 函数不起作用

使用 Getchar 时清除缓冲区(必须有更好的方法!)

c - 无论如何,我不能在我的 Eclipse 中使用 fflush 来获得正确的控制台?