[英]When using a while loop to traverse a linked list, why does my loop iterate by twice the number of nodes in the list?
[英]why does my int while loop keeps going when i scan for a number?
我在while循環中遇到問題。 我必須輸入一個大於0且小於81的數字。當我使用-1,0,1,2,82之類的數字時,它會變好並得到預期的結果,但是當我使用字母時,它會繼續通過我的while循環。 我在eclipse中使用了調試器,當我處於while循環時,由於scanf失敗,循環amount
自動設置為“ 0”。 為什么插入字母時它會不斷循環播放?
#include <stdio.h>
#include <stdlib.h>
int main(){
int amount = 0;
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
while(amount <= 0 || amount >= 81){
printf("Wrong input try again.\n");
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
}
return EXIT_SUCCESS;
}
您需要確保scanf()
有效。 使用返回值執行此操作
if (scanf("%d", &amount) != 1) /* error */;
當它不起作用時(例如在輸入中找到一個字母),您可能想擺脫錯誤的原因。
從用戶那里獲取輸入的更好的選擇是使用fgets()
看到這個相關的問題: scanf()不等待用戶輸入
原因是當您按Enter鍵並輸入一個字符時,scanf失敗,並且沒有吞噬輸入提要中的字符。 結果,下一個塊開始具有您之前輸入的內容。
您可以通過在while
循環中的scanf()
之前添加getchar()
來進行檢查。 您會注意到,它會重復while循環,直到您的行中包含無效字符為止,然后停止並等待輸入。 每次循環運行時, getchar()
在輸入中使用無效字符之一。
不過,最好不要使用scanf
這樣的。 看看這個資源: 用scanf()讀一行不好嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.