[英]writing in c with printf and scanf not working as expected
所以我完全是 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
任何見解? 我期待它printf,然后scanf 為用戶輸入像這樣:
Enter the box length: (waits for user int input; ex. 8 + "Enter")
Enter the box width: ...
只需添加fflush(stdout);
在調用scanf()
之前的每個printf()
之后:
#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;
}
您可以簡單地在每個 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.