2014-02-27 33 views
1

在我的程序中,我只是計算事物的成本。然而,最後我想在程序上稍微休息一下,要求用戶只需按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); 
} 
+0

由於您未測試結果,因此無法判斷它是否正常工作。這是工作;它在棋盤上的賓館數量('scanf()'留下不被輸入中的轉換規範讀取的字符)之後返回換行符。你可能會發現閱讀整行很容易,然後用'sscanf()'掃描它們。你應該考慮使用'scanf()'來執行轉換並檢查沒有錯誤,使用'if(scanf(「%d」,&hotels)!= 1){... report error ...}。 –

+0

[getchar不會在使用scanf時停止](http://stackoverflow.com/questions/12653884/getchar-does-not-stop-when-using-scanf) –

+0

'getchar();' - > 'getchar(); getchar();' – BLUEPIXY

回答

0

我最好的猜測是它在用戶輸入他們的輸入後檢索剩餘的換行符。您可以打印出返回值進行驗證。如果我是正確的,取決於您的操作系統,它將是「10」或「13」。

您可能想要更改程序以使用getline。在How to read a line from the console in C?

+1

如果'getchar()'讀取換行符,它將返回''\ n'',通常等於10.在文本模式下,每行換行符都將被轉換爲一個換行符,並且每個換行符在輸出時被轉換爲行尾序列。 (在類UNIX系統上,轉換是微不足道的。) –

0

如何編寫獲取線還有其他示例當代碼調用scanf("%s", ...程序等待輸入。

您輸入「123」,但沒有任何反應,因爲stdin是緩衝輸入,並等待\n,因此係統未給出任何數據給scanf()

然後你輸入「\ n」和「123 \ n」給出stdin

scanf("%s",...)讀取stdin並掃描可選的前導空白,然後掃描非空白空間「123」。最後它看到「\ n」並將其放回stdin並完成。代碼scanf("%s", ...再次。 scanf()掃描「\ n」作爲其掃描可選領先空白的一部分。然後它等待更多的輸入。

您鍵入「456」並且什麼也沒有發生,因爲stdin是緩衝輸入並等待\n,因此係統沒有給出任何數據給scanf()

然後你輸入「\ n」和「456 \ n」給出stdin

scanf("%s",...)讀取stdin並掃描可選的前導空白,然後掃描非空白空間「456」。最後它看到「\ n」並將其放回stdin並完成。

最後你可以撥打getchar()並吸氣,它會從stdin讀取上一行的\n


那麼,我該如何停止程序,要求輸入getchar()以及如何讓它只識別一個輸入按鈕。

最佳方法:使用fgets()

char hotels_houses[5+1]; 

// scanf("%s", hotels_houses); 
fgets(hotels_houses, sizeof hotels_houses, stdin); 
houses = atoi(hotels_houses); 
... 
// scanf("%s", hotels_houses); 
fgets(hotels_houses, sizeof hotels_houses, stdin); 
hotels = atoi(hotels_houses); 
... 
puts("Click enter to calculate total cash "); 
fgets(bhotels_houses, sizeof hotels_houses, stdin); // do nothing w/hotels_houses 
printf("Total cost: %d\n", cost); 

fgets()檢查一個NULL返回值是測試一個封閉stdin有用。
使用strtol()atoi()相比具有錯誤檢查優勢。

相關問題