Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c - Flush output buffer every N chars

I would like to flush my buffer after every three characters are typed in (instead of the ). What would be the proper way to change the line-buffer trigger to be from being to being every 3 chars?

So far I have something like this:

#include<stdio.h>
#define CHAR_BUFFER 3

int main(void)
{

    int ch;
    int num=0;

    while ((ch = getchar()) != EOF) {
        if (ch == '
') continue; // ignore counting newline as a character
        if (++num % CHAR_BUFFER == 0) {
            printf("Num: %d
", num);
            fflush(stdout);
            putchar(ch);
            
        }
    }

    return 0;
}

What the program currently produces is:

$ main.c
Hello how are you?
Num: 3
lNum: 6
 Num: 9
wNum: 12
rNum: 15
yNum: 18
?

So instead of printing out all three chars, it seems to only grab the last one. What would be the correct way to do this?

Here are two examples of what I want:

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]
question from:https://stackoverflow.com/questions/65909119/flush-output-buffer-every-n-chars

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

putchar() shouldn't be inside the if. You want to print all the characters, the condition is just for flushing.

#include<stdio.h>
#define CHAR_BUFFER 3

int main(void)
{

    int ch;
    int num=0;

    while ((ch = getchar()) != EOF) {
        if (ch == '
') continue; // ignore counting newline as a character
        putchar(ch);
        if (++num % CHAR_BUFFER == 0) {
            printf("Num: %d
", num);
            fflush(stdout);            
        }
    }

    return 0;
}

Note that this is for flushing the output buffer. It has nothing to do with how input is read or echoed, which requires using OS-specific functions.

See Capture characters from standard input without waiting for enter to be pressed and ANSI C No-echo keyboard input


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...