在我的程序中,我只是計算事物的成本。然而,最後我想在程序上稍微休息一下,要求用戶只需按Enter按鈕。我認爲getchar()可以在這裏工作,但它甚至不會停止,它只是繼續保持打印。我甚至試圖在scanf(「%s」)之類的稀疏格式之後放置一個空格。爲什麼我的getchar()不在這裏工作?
因此,兩件事我該如何阻止程序在getchar()處要求輸入,以及如何讓它只識別一個輸入按鈕。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char hotels_houses[5];
int houses, hotels, cost;
printf("Enter amount of houses on board: \n");
scanf("%s", hotels_houses);
houses = atoi(hotels_houses);
printf("Enter amount of hotels on board: \n");
scanf("%s", hotels_houses);
hotels = atoi(hotels_houses);
printf("Cost of houses: %d\n", houses);
printf("Cost of hotels: %d\n", hotels);
cost = (houses *40) + (hotels * 115);
puts("Click enter to calculate total cash ");
getchar(); /* just a filler */
printf("Total cost: %d\n", cost);
return(0);
}
由於您未測試結果,因此無法判斷它是否正常工作。這是工作;它在棋盤上的賓館數量('scanf()'留下不被輸入中的轉換規範讀取的字符)之後返回換行符。你可能會發現閱讀整行很容易,然後用'sscanf()'掃描它們。你應該考慮使用'scanf()'來執行轉換並檢查沒有錯誤,使用'if(scanf(「%d」,&hotels)!= 1){... report error ...}。 –
[getchar不會在使用scanf時停止](http://stackoverflow.com/questions/12653884/getchar-does-not-stop-when-using-scanf) –
'getchar();' - > 'getchar(); getchar();' – BLUEPIXY