C 之前的代码,而(1)不运行
我有如下代码:C 之前的代码,而(1)不运行,c,ansi-c,C,Ansi C,我有如下代码: #include <stdio.h> int main(int argc, char *argv[]) { printf("hello"); while(1){ // whatever here } } #包括 int main(int argc,char*argv[]){ printf(“你好”); 而(1){ //随便这里 } } 问题是:为什么跳过第一条指令?它只运行循环,从不打印hello。我用gcc和g++编译
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello");
while(1){
// whatever here
}
}
#包括
int main(int argc,char*argv[]){
printf(“你好”);
而(1){
//随便这里
}
}
问题是:为什么跳过第一条指令?它只运行循环,从不打印hello。我用gcc和g++编译了它,结果是一样的。你的假设是错误的,你的代码确实在运行,只是
stdout
没有被刷新,而是被缓冲
在printf(“hello”)
之后使用fflush(stdout)
,这将强制打印stdout
而且,正如@Bathsheba指出的,
printf
中的换行符(“\n”
)也会强制它刷新,这一点已经解释清楚了。它会运行,只是在运行时,不会刷新输出缓冲区
使用printf(“hello\n”)代码>取而代之。换行符将刷新缓冲区,以便将输出立即写入控制台。问得好。完整的源代码和容易理解的问题。(+1)