2015-12-09 74 views
0

當輸入高度時,會創建一個類似馬里奧的金字塔。處理錯誤,無限循環

#include <stdio.h> 

int main(void) 
{ 
    int height; 
    char signal = 'n'; 

    while (signal != 'y') 
    { 
    printf("Height: "); 
    scanf("%d", &height); 

    if (height <= 0) 
    { 
     printf("Error. Positive #s only. \n"); 
    } 
    else if (height > 23) 
    { 
     printf("Error. # must be from 0-23. \n"); 
    } 
    else if (height > 0 || height <= 23) 
    { 
     signal = 'y'; 
    } 
    else 
    { 
     printf("Can you bulid a pyramid with letters? I thought so... \n"); 
    } 
    } 

    int i, j, k; 

    for (i = 1; i <= height; i++) 
    { 
    if (height <= 8) 
     printf("\t"); 
    else if (height <= 16) 
     printf("\t\t"); 
    else if (height <= 23) 
     printf("\t\t\t"); 

    for (k = 0; k < i; k++) 
    { 
     printf("\b"); 
    } 

    for (j = 0; j <= i; j++) 
    { 
     printf("#"); 
    } 
    printf("\n"); 
    } 
} 

如果用戶決定傻傻地輸入字符串,程序會進入無限循環。我認爲該程序將使用else語句,但不會。我該如何處理?

+0

請編輯您的帖子和修復縮進。 – Lundin

回答

2

您需要檢查返回值scanf,它返回匹配和分配的輸入項目的數量。如果輸入文本,則不匹配任何內容,文本保留在輸入緩衝區中。因此scanf一直試圖在循環的每次迭代中讀取相同的不匹配數據。

通過檢查返回值,可以判斷是否輸入了字符串。您還需要通過調用getchar來清除輸入緩衝區,直到獲得換行符。

試試這個:

int items = scanf("%d", &height); 

    if (items < 1) { 
     int ch; 
     printf("Please enter a number\n"); 
     while (((ch=getchar()) != '\n') && (ch != EOF)); 
    else if(height <= 0) 
    ... 
+0

理想情況下,getchar()循環也應該檢查EOF,否則會冒無限期運行的風險。 – Medinoc

+0

@Medinoc良好的通話。編輯。 – dbush

2

scanf()返回一個值,指示已成功讀取多少個值。如果它是零,則意味着什麼都不能被讀取。您應該使用此值來檢查輸入中的錯誤。