如何刷新控制台缓冲区? [英] How to flush the console buffer?

查看:223
本文介绍了如何刷新控制台缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code,它repetedly运行:

i have some code that run repetedly :

的printf(你要继续Y / N:吗?\\ n);结果
  keepplaying =的getchar();

printf("do you want to continue? Y/N: \n");
keepplaying = getchar();

在今后我code运行时它不等待输入。
我发现的getchar在seconed时使用的'\\ n'作为字符内。
IM居兴,这是由于一些缓冲SDIO了,所以它保存最后输入这是Y \\ n或N \\ N。

in the next my code is running it doesnt wait for input. i found out that getchar in the seconed time use '\n' as the charcter. im gussing this is due to some buffer the sdio has, so it save the last input which was "Y\n" or "N\n".

我的Q是,我如何使用getchar函数,这将使的getchar等待我的回答之前刷新缓冲区?

my Q is, how do i flush the buffer before using the getchar, which will make getchar wait for my answer?

推荐答案

刷新输入流导致不确定的行为。

Flushing an input stream causes undefined behaviour.

INT fflush(FILE * ostream的);

int fflush(FILE *ostream);

的ostream指向一个输出流或
  更新流,其中,最
  最近的操作不是输入,
  fflush函数导致任何不成文
  该流数据被传递
  到主机环境要被写入
  到该文件;否则,该行为
  未定义。

ostream 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.

要适当清空输入流做类似如下:

To properly flush the input stream do something like the following:

int main(void)
{
  int   ch;
  char  buf[BUFSIZ];

  puts("Flushing input");

  while ((ch = getchar()) != '\n' && ch != EOF);

  printf ("Enter some text: ");

  if (fgets(buf, sizeof(buf), stdin))
  {
    printf ("You entered: %s", buf);
  }

  return 0;
}

请参阅为什么fflush(标准输入)是错误的刷新输入缓冲区

这篇关于如何刷新控制台缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆