在CDT中命令台printf的输出缓冲问题:

Ask:

The eclipse console has weird behaviour when used for input with C programs.
I teach C to first year undergraduates and I want them to learn their way through eclipse. But the small silly programs that ask you to input characters have weird behaviour, if you use the eclipse console. It seems like it groups all input and output commands and executes them together…for example… the following program:

#include <stdio.h>

int main(void) {

int n = 0;

printf(“Gimme a number: “);

scanf(“%d”, &n);

printf(”
The number you entered was %d
“, n);

return 0;

}

 

has the following output:

4

Gimme a number: The number you entered was 4

Pretty normal output on any console you’ll find, not just with eclipse’s one instead of

Gimme a number: 4

The number you entered was 4

 

Answer:

To obtain this output, you have to flush stdout before scanf’ing the number. The output is flushed either implicitely when a newline character is echoed on the console (printf(”
“)) or explicitely with fflush(stdout);

 

ps: printf() 语句将输出传递给缓冲区的中介存储区,然后缓冲区的内容再不断地被传递给屏幕,C标准规定,有3种情况会将缓冲区的内容传递给屏幕:缓冲区满的时候,需要 输入的时候以及遇到换行符。所以说a newline character is echoed on the console,早期的c语言经常这样做的,例如:

printf(“Hello
”);

scanf(…..);

不过在eclipse中只能使用ffush( stdout )。将缓冲区的内容传递给屏幕或文件就叫做刷新缓冲区(flushing the buffer)』

 

to get the output you wanted use this program :

#include <stdio.h>

int main(void) {

int n = 0;

printf(“Gimme a number: “);

fflush(stdout);

scanf(“%d”, &n);

printf(”
The number you entered was %d
“, n);

return 0;

}

 

fromhttp://dev.eclipse.org/newslists/news.eclipse.tools.cdt/msg08763.html

来源: CDT中prinft的输出问题_某萤火虫_百度空间

- EOF -