C编程 - 不确定输入在print语句之前的原因

时间:2014-04-13 03:15:56

标签: c

我正在尝试理解移动和屏蔽,我从这里找到了这段代码......

https://answers.yahoo.com/question/index?qid=20120812164745AAn4i6L

当我运行程序时,我必须输入一个输入才能看到“输入数字......”。代码似乎对我好,所以不确定为什么print语句不会首先出现。我错过了什么吗?我对C很新,但对我来说还不错

#include <stdio.h>

int main(void) {

    unsigned int hex, h1, h2, h3, h4;
    printf("enter a eight-digit hex value: \n");
    scanf("%x", &hex);
    /* bit masking */
    h1= hex & 0x000000ff;
    h2= hex & 0x0000ff00;
    h3= hex & 0x00ff0000;
    h4= hex & 0xff000000;
    /*shift bits to right as indicated */

    printf("%x\n", h1);
    printf("%x\n", h2);
    printf("%x\n", h3);
    printf("%x\n", h4);

    h2 >>= 8;
    h3 >>= 16;
    h4 >>= 24;
    /* print output */
    printf("\n 0x%08x is composed of %02x %02x %02x %02x\n",
           hex, h4, h3, h2, h1);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

默认情况下,如果没有将stdout定向到终端,则缓冲它。如果您在IDE中运行,则可能无法正确模拟终端。因此要么显式地使用setbuf使stdout无缓冲或行缓冲,要么在读取输入之前需要看到的printf之后调用fflush(stdout)。