1

我在 Windows 10 x86 64 位计算机上运行 Netbeans 8.1,我将项目的 Run>Console Type 设置为 Standard Output,因为内部和外部终端都不适用于我制作的任何其他来源——为此标准输出了。无论如何,这是我试图运行的代码:

int main(void){

float original_amount, amount_with_tax;

printf("Enter an amount: ");
scanf("%f", &original_amount);
amount_with_tax = original_amount * 1.05f;
printf("With tax added: $%.2f\n", amount_with_tax);

exit(EXIT_SUCCESS);
}

这是输出:

3
输入金额:加税:$3.15

运行成功(总时间:4s)

如您所见,扫描功能在程序甚至打印“输入金额:”之前读取数字。此外,在我注释掉 scanf 函数后,它按预期打印了两个 printf 语句。我一直在努力解决这个问题一段时间,感谢任何帮助,谢谢!

4

1 回答 1

0

ISO/IEC 9899:201x:

Files

… When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. …</p>

Your standard output stream seems to be line buffered, which is most often so.

try printf("Enter an amount: ");fflush(stdout); – BLUEPIXY

That worked! Is this only necessary because I'm using the standard output as my run console?

No, other streams opened by your program may even be fully buffered.

And if so, should I just put it at the beginning of any program that will use a function accessing the buffer?

Putting fflush(stdout) at the beginning of a program won't do, since it outputs only once what is already in the stdout buffer. But you can use setbuf(stdout, NULL) there.

于 2016-06-23T11:06:10.113 回答