打印语句不会在无限循环之前打印 [英] Print statement won't print before an infinite loop
问题描述
在尝试调试某些C代码时,我注意到将printf()置于无限循环之前将无法执行。有人知道为什么是这样吗?实际上,这没什么大不了的,但是对于调试来说,这是一场噩梦。
While trying to debug some C code I noticed that a printf() won't execute if placed before an infinite loop. Does anyone know why this is? Practically it's not that big of a deal, but for debugging it's a nightmare.
#include<stdio.h>
int main()
{
int data;
printf("This prints fine.\n");
printf("Enter data: ");
scanf("%d", &data);
printf("This should print but it doesn't.\n");
while(1)
{
//Infinite Loop
}
return 0;
}
推荐答案
在调用printf()时,程序终止或遇到换行符后,将显示输出。
但是由于在printf()之后调用无限循环,程序不会终止并且不会显示缓冲区的输出。
On calling printf() , output is displayed after program terminates or newline character is encountered. But since you are calling infinite loop after printf() , program doesn't terminate and output from buffer is not displayed.
使用 fflush(stdout)
强制显示缓冲区输出
Use fflush(stdout)
to force output from buffer to be displayed
stdout
标准输出流是应用程序输出的默认目标。在大多数系统中,默认情况下通常将其定向到文本控制台(通常在屏幕上)。
stdout
The standard output stream is the default destination of output for applications. In most systems, it is usually directed by default to the text console (generally, on the screen).
fflush()
函数使系统清空缓冲区
The fflush()
function causes the system to empty the buffer
这篇关于打印语句不会在无限循环之前打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!