2014-10-16 55 views
2

我試圖讓這個循環運行,直到給出一個非數字輸入。問題是,當我輸入一個字母來退出while循環時,它會進入無限循環。它也進入第一個if語句並繼續循環。如果有人對如何解決這個問題有任何想法,那會很好。輸入退出條件後陷入無限循環。

int counter; 
int input[100] 
int num = 1 
while (input[num] == 0) 
{ 
    printf("score #%d:", counter); 
    scanf("%d",&input[num]); 

    if (input[num] <= 0){ 
     printf("you cannot use negative numbers\n"); 
     continue; 
    } 
    if (input[num] >= 100){ 
     printf("you cannot use numbers greater than 100\n"); 
     continue; 
    } 
    num++; 
    counter++; 

} 

回答

2

首先,num應該是0作爲數組索引從0而不是1

然後開始,你在while條件有input[num]==0。您使用未初始化的變量進行測試,因爲input尚未初始化。這與counter相同。

,你已經錯過了;第2行的結束和3

最後,用下面的代碼替換您scanf您的代碼將無法編譯:

if(scanf("%d",&input[num])==0) 
{printf("non-numeric character entered .Exiting loop...\n"); 
scanf("%*s");// asterick tells scanf to discard scanned string(clear the entered char) 
break; 
} 

所以最後,修改後的代碼:

int counter=1; // initialize variable 
int input[100]; //semicolon here 
int num = 0; //num must be 0 
while (1) //infinite loop 
{ 
    printf("score #%d:", counter); 

    if(scanf("%d",&input[num])==0) //if no value is scanned 
{printf("non-numeric character entered .Exiting loop...\n"); 
scanf("%*s");// asterick tells scanf to discard scanned string(clear the entered char) 
break; 
} 

    if (input[num] <= 0) 
     printf("you cannot use negative numbers\n"); 

    else if (input[num] >= 100) 
     printf("you cannot use numbers greater than 100\n"); 
    else{ 
    num++; 
    counter++;} 

} 
4

的問題是,當scanf當您嘗試與%d格式閱讀設置有非數字輸入,非數字的數據不會從緩衝區中刪除。當循環再次到達scanf時,它會得到相同的數據,並在無限循環中繼續失敗。

爲了解決這個問題,刪除非數字輸入時scanf不讀項目的適當數量:

int readCount = scanf("%d",&input[num]); 
if (readCount != 1) { 
    scanf("%*s"); 
    printf("Please enter a valid number.\n"); 
    continue; 
} 

請注意,你的循環的結束條件是不正確的,因爲num總是過去有最後一個元素被讀過。你能解決這個問題是這樣的:

所有的
while (num < 100) 
{ 
    ... // Read and error checks go here 
    if (input[num] == 0) { 
     break; 
    } 
    num++; 
    counter++; 
} 
+0

+1,用於很好地使用'「%* s」'。可能想提到關於'EOF'。 – chux 2014-10-16 16:29:46

+0

這是否會使我在輸入字母時會跳出循環?我認爲當輸入是一個數字時,'input [num] == 0'是真的。那麼這不會打破任何輸入號碼的循環? – Chris 2014-10-16 16:31:37

+0

@Chris問題是,當你在'while'循環的頭部檢查'input [num] == 0'時,'num'已經從最後一個輸入存儲的位置「加1」。如果用戶輸入一個非數字值,循環將繼續,因爲在scanf(「%* s」)之後使用'continue'運算符。 – dasblinkenlight 2014-10-16 16:34:22