使用printf和scanf写入c不能按预期工作

Chr*_*ava 2 c printf scanf

所以我是C的新手.我正在使用带有MinGW编译器的eclipse.我在第二章使用scanf和printf函数,我的程序正在运行,但只有在我将三个int输入scanf函数后才将语句打印到控制台.

#include <stdio.h>
int main(void){
    int length, height, width, volume, dweight;

    printf("Enter the box length: ");
    scanf("%d", &length);
    printf("\nEnter the box width: ");
    scanf("%d", &width);
    printf("\nEnter the box height");
    scanf("%d", &height);

    volume = length * width * height;
    dweight = (volume + 165) / 166;

    printf("Dimensions: l = %d, w = %d, h = %d\n", length, width, height);
    printf("Volume: %d\n", volume);
    printf("Dimensional Width: %d\n", dweight);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

控制台输出:

8 (user input + "Enter" + key)
10 (user input + "Enter" key)
12 (user input + "Enter" key)
Enter the box length: 
Enter the box width: 
Enter the box heightDimensions: l = 8, w = 10, h = 12
Volume: 960
Dimensional Width: 6
Run Code Online (Sandbox Code Playgroud)

任何见解?我期待它到printf,然后scanf用户输入如下:

Enter the box length: (waits for user int input; ex. 8 + "Enter")
Enter the box width: ...
Run Code Online (Sandbox Code Playgroud)

pho*_*ger 5

在致电之前,请fflush(stdout);在每次printf()之后添加scanf():

#include <stdio.h>
int main(void){
    int length, height, width, volume, dweight;

    printf("Enter the box length: "); fflush(stdout);
    scanf("%d", &length);
    printf("\nEnter the box width: "); fflush(stdout);
    scanf("%d", &width);
    printf("\nEnter the box height"); fflush(stdout);
    scanf("%d", &height);

    volume = length * width * height;
    dweight = (volume + 165) / 166;

    printf("Dimensions: l = %d, w = %d, h = %d\n", length, width, height);
    printf("Volume: %d\n", volume);
    printf("Dimensional Width: %d\n", dweight);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 在你的系统上,stdout中的文本仍保留在内存中,并等待你打印出足够多的东西填充内部缓冲区,否则你明确地刷新了缓冲区的内容.这是出于效率原因.缓冲输出通常是更有效的I/O ...系统将缓冲区作为单个大块输出发送,而不是一次一点点.在你的情况下,这不是你想要的行为.在这方面,不同的系统可能表现完全不同; 它是依赖于实现的行为. (2认同)
  • 顺便提一下,另一个可能触发刷新的事件是您的程序退出.因此,如果你已经编程了一段时间而且从来没有这样做过,那是因为你可能从未使用过scanf().另一种可能性是输出流中的''\n'`可能触发刷新.触发刷新不需要换行符,但在某些系统上可能会这样做. (2认同)