[英]How to get integer input in an array using scanf in C?
我正在使用 scanf 獲取多個整數輸入並將其保存在一個數組中
while(scanf("%d",&array[i++])==1);
輸入整數由空格分隔,例如:
12 345 132 123
我在另一篇文章中閱讀了這個解決方案。
但問題是 while 循環沒有終止。
這個說法有什么問題?
OP 使用Enter或'\\n'
來指示輸入的結尾和空格作為數字分隔符。 scanf("%d",...
不區分這些空格。在 OP 的while()
循環中, scanf()
消耗'\\n'
等待額外的輸入。
相反,使用fgets()
讀取一行,然后使用sscanf()
、 strtol()
等來處理它。 ( strtol()
是最好的,但 OP 使用的是scanf()
系列)
char buf[100];
if (fgets(buf, sizeof buf, stdin) != NULL) {
char *p = buf;
int n;
while (sscanf(p, "%d %n", &array[i], &n) == 1) {
; // do something with array[i]
i++; // Increment after success @BLUEPIXY
p += n;
}
if (*p != '\0') HandleLeftOverNonNumericInput();
}
//Better do it in this way
int main()
{
int number,array[20],i=0;
scanf("%d",&number);//Number of scanfs
while(i<number)
scanf("%d",&array[i++]);
return 0;
}
你應該試着像這樣寫你的陳述:
while ( ( scanf("%d",&array[i++] ) != -1 ) && ( i < n ) ) { ... }
請注意邊界檢查。
正如人們一直說的那樣,在解析來自正常人類的真實輸入時,scanf 不是您的朋友。 它在處理錯誤情況時存在許多陷阱。
也可以看看:
您的代碼沒有任何問題。 並且只要輸入的整數個數不超過數組的大小,程序就會一直運行,直到輸入EOF。 即以下作品:
int main(void)
{
int array[20] = {0};
int i=0;
while(scanf("%d", &array[i++]) == 1);
return 0;
}
正如 BLUEPIXY 所說,您必須為 EOF 輸入正確的擊鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.