2016-03-10 15 views
-1

這段代碼在輸入字母時連續打印「輸入數組值:只能輸入數字值」。我不明白爲什麼它不只是打印一次,而是繼續接受輸入。理想情況下,用戶將重新輸入一個或整個值集,以便使用剛剛退出循環的break命令並不理想。任何建議的話將不勝感激。troublebeshooting爲什麼代碼段卡在循環中

#include <stdio.h> 
#include <string.h> 

int main(void) 
{ 
int i, value, containsValues[5]; 

for(i=0; i<=4;) { 
    printf("Enter array value: \n"); 

    if (scanf("%d", &value) !=1) 
    { printf("Only numeric values can be entered \n");} 
    else 
    {containsValues[i] = value; 
    ++i;} 
} 

return 0; 
} 

編輯:信件是否留在導致此行爲的緩衝區中?如果是的話,清除緩衝區的任何提示?

+0

調試提示:打印變量「i」和「value」的內容。還檢查'scanf()' – Coconop

+0

謝謝你的提示返回!但即使我增加了用戶不能再輸入輸入提示? –

回答

0

它進入了無限循環,因爲您沒有打破無效輸入 - 索引i從未增加。

放一個break爲無效的輸入:

if (scanf("%d", &value) !=1) 
{ 
    printf("Only numeric values can be entered \n"); 
    break; 
} 
+0

我試過放置一箇中斷,但是這樣可以防止進一步的輸入,就像改變for循環中增量的位置。都停止垃圾郵件,但我希望用戶能夠重新輸入值 –

1

你有一個錯誤的輸入後清除輸入緩衝區,使用此for循環:它循環,直到輸入正確值

for (i = 0; i <= 4;) 
{ 
    printf("Enter array value: \n"); 
    if (scanf("%d", &value) != 1) 
    { 
     printf("invalid input\n"); 
     fflush(stdin); 
     continue; 
    } 
    containsValues[i] = value; 
    ++i; 
} 
+1

非常感謝我意識到我的錯誤,並在那裏放入一個偷偷摸摸的scanf來吸收無效輸入! –

相關問題