Print statement won't print before an infinite

2019-07-20 08:20发布

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;
}

3条回答
Luminary・发光体
2楼-- · 2019-07-20 08:56

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.

Use fflush(stdout) to force output from buffer to be displayed

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).

The fflush() function causes the system to empty the buffer

查看更多
\"骚年 ilove
3楼-- · 2019-07-20 09:10

try __fpurge(stdout) It will clear your output buffer

查看更多
手持菜刀,她持情操
4楼-- · 2019-07-20 09:10

Their is a concept called line buffer and block buffer. Every thing what you want to write to the screen will be in buffer. line buffer means when ever new line [\n] found it"ll flush the buffer that means your string will print on the screen. block buffer means their will be fixed size for block until unless that block full it"ll not print on the screen. in the above case new line [\n] is enough to print

查看更多
登录 后发表回答