所以我是C的新手。我正在使用带有MinGW编译器的eclipse。 我在第二章使用scanf和printf函数,我的程序正在运行,但只有在我将三个整数输入scanf函数后才将语句打印到控制台。
#include 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 = %dn", length, width, height); printf("Volume: %dn", volume); printf("Dimensional Width: %dn", 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
任何见解? 我期待它到printf,然后scanf用户输入如下:
Enter the box length: (waits for user int input; ex. 8 + "Enter") Enter the box width: ...
只需添加fflush(stdout);
在调用scanf()
之前每个printf()
之后:
#include 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 = %dn", length, width, height); printf("Volume: %dn", volume); printf("Dimensional Width: %dn", dweight); return 0; }
处理C中的Dirty Buffers !!
您可以在每个printf()的末尾添加一个换行符(转义序列)’ n’ ,这用于刷新缓冲区,最终启用输出终端上的显示。( fflush实现了相同的function(stdout) )但是每次调用printf()时都没有必要写它,只需要包含一个字符’ n’ )
注意:始终建议使用’ n’字符作为printf()的引号“”内的最后一个元素,因为除非使用了刷新机制,否则数据将保留在缓冲区内,但是当缓冲区被自动刷新时main()函数结束,此外,只有在刷新临时缓冲区时,数据才会到达目标。
我们的新代码应如下所示:
#include 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 = %dn", length, width, height); printf("Volume: %dn", volume); printf("Dimensional Width: %dn", 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
以上就是c/c++开发分享使用printf和scanf写入c不能按预期工作相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/549973.html