Print statement won't print before an infinite loop

大兔子大兔子 提交于 2019-12-11 03:47:07

问题


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

回答1:


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




回答2:


try __fpurge(stdout) It will clear your output buffer




回答3:


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



来源:https://stackoverflow.com/questions/13667625/print-statement-wont-print-before-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!