c - 每 N 个字符刷新一次输出缓冲区
问题描述
我想在每输入三个字符后刷新我的缓冲区(而不是\n
)。将行缓冲区触发器从\n
每 3 个字符更改为每 3 个字符的正确方法是什么?
到目前为止,我有这样的事情:
#include<stdio.h>
#define CHAR_BUFFER 3
int main(void)
{
int ch;
int num=0;
while ((ch = getchar()) != EOF) {
if (ch == '\n') continue; // ignore counting newline as a character
if (++num % CHAR_BUFFER == 0) {
printf("Num: %d\n", num);
fflush(stdout);
putchar(ch);
}
}
return 0;
}
该程序目前产生的是:
$ main.c
Hello how are you?
Num: 3
lNum: 6
Num: 9
wNum: 12
rNum: 15
yNum: 18
?
所以不是打印出所有三个字符,它似乎只抓住最后一个。这样做的正确方法是什么?
这是我想要的两个示例:
H<enter>
// [nothing returned since we have not yet hit our 3rd character]
el<enter>
Hel // [return 'Hel' since this is now a multiple of three]
解决方案
putchar()
不应该在if
. 您要打印所有字符,条件仅用于冲洗。
#include<stdio.h>
#define CHAR_BUFFER 3
int main(void)
{
int ch;
int num=0;
while ((ch = getchar()) != EOF) {
if (ch == '\n') continue; // ignore counting newline as a character
putchar(ch);
if (++num % CHAR_BUFFER == 0) {
printf("Num: %d\n", num);
fflush(stdout);
}
}
return 0;
}
请注意,这是用于刷新输出缓冲区。它与如何读取或回显输入无关,这需要使用特定于操作系统的函数。
推荐阅读
- python - PyQt5 窗口出现空
- html - 在 Crome 上显示黑屏的 html 视频
- azure-ad-b2c - B2C 密码重置策略强制登录进入忘记密码流程
- git - 如何从 .gitignore 中删除某些文件目录关于 Git
- python - 如何用科学记数法(张量格式)解析文本文件并将它们转换为浮点数
- spring-boot - 为什么 Spring Converter 没有抛出异常?
- grails - CSV 插件控制器在哪里?
- azure-synapse - Synapse Spark Pool 在配置状态下挂起:删除错误
- raspberry-pi - Raspberry Pi dhcp-exit-hooks 适用于 wlan0 但不适用于 eth0
- python-3.x - 使用 BeautifulSoup - Python 从 www.transfermarkt.co.uk 抓取数据