为什么C到while循环卡住半途而废? [英] Why would C get stuck halfway through a while loop?

查看:260
本文介绍了为什么C到while循环卡住半途而废?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译和运行这个code(这是一个更大的计划的一部分),Linux的通过,而循环中途变,后来干脆停止工作。

在code下面打印时间:0 ,然后挂起,什么也不做,直到我停止的过程。为什么地球上会打印时间:0 但不完整性检查的以下行

 而(I< 5)
{
    的printf(时间:%d个\\ N,elapsedTime);
    的printf(健康检查);
    富();
    我++;
}


解决方案

输出通常被缓冲,只有经过冲洗或换行写的。在

 的printf(健康检查);

没有换行,所以如果你在这之后的无限循环中运行,你不会看到它。
它替换为

 的printf(健康检查\\ n);

 的printf(健康检查);
fflush(标准输出);

和你会看到它。

When I compile and run this code (it's part of a much larger program), Linux gets halfway through the while loop, then simply stops working.

The code below prints time: 0 and then hangs, doing nothing else until I suspend the process. Why on earth would it print time: 0 but not the following line of sanity check?

while (i < 5)
{
    printf("time: %d\n",elapsedTime);
    printf("sanity check");
    foo();
    i++;
}

解决方案

Output usually is buffered and only written after a flush or newline. In

printf("sanity check");

there is no newline, so if you run in an endless loop after this, you won't see it. Replace it with

printf("sanity check\n");

or

printf("sanity check");
fflush(stdout);

and you'll see it.

这篇关于为什么C到while循环卡住半途而废?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆