2

所以我是 C 的新手。我正在使用 eclipse 和 MinGW 编译器。我在使用 scanf 和 printf 函数的第二章,我的程序正在运行,但只有在我将三个整数输入 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;
}

控制台输出:

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

有什么见解吗?我期待它打印,然后扫描用户输入,如下所示:

Enter the box length: (waits for user int input; ex. 8 + "Enter")
Enter the box width: ...
4

2 回答 2

6

只需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;
}
于 2013-09-17T19:00:28.127 回答
1

在 C 中处理脏缓冲区!

您可以简单地在每个 printf() 的末尾包含一个换行符(转义序列)'\n' ,这用于刷新缓冲区,最终启用输出终端上的显示。(相同的功能由 fflush(stdout ) 但不需要每次调用 printf() 时都写,只需包含一个字符 '\n' )

注意:始终建议使用 '\n' 字符作为 printf() 的引号 "" 内的最后一个元素,因为除非使用刷新机制,否则数据将保留在缓冲区中,但是当main() 函数结束,此外,只有在刷新中间缓冲区时,数据才会到达目的地。

我们的新代码应如下所示:

#include <stdio.h>
int main(void){
    int length, height, width, volume, dweight;
    printf("Enter the box length: \n");
    scanf("%d", &length);
    printf("\nEnter the box width: \n");
    scanf("%d", &width);
    printf("\nEnter the box height \n");
    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;
}

控制台输出:

Enter the box length: 
8
Enter the box width:  
10
Enter the box height 
12
Dimensions: l = 8, w = 10, h = 12
Volume: 960
Dimensional Width: 6
于 2017-07-17T16:47:40.377 回答