首页 > 解决方案 > 每 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]

标签: c

解决方案


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;
}

请注意,这是用于刷新输出缓冲区。它与如何读取或回显输入无关,这需要使用特定于操作系统的函数。

请参阅 从标准输入捕获字符而不等待按下回车ANSI C 无回显键盘输入


推荐阅读