eclipse中的关于scanf和printf的输入顺序的解决办法

本文探讨了在Eclipse环境中运行C程序时遇到的一个奇怪现象:输入和输出操作似乎被成组执行,导致程序行为不符合预期。通过使用fflush(stdout)解决此问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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() {
int n = 0;
printf("Gimme a number: ");
scanf ("%d", &n);
printf("/nThe number you entered was %d/n", 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

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("/n")) or explicitely with fflush(stdout);


to get the output you wanted use this program :


#include <stdio.h>


int main()  {


    int n = 0;
    printf("Gimme a number: ");
    fflush(stdout);
    scanf ("%d", &n);
    printf("/nThe number you entered was %d/n", n);


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值