![](/img/trans.png)
[英]How to scan for user input of both strings and ints to put into a 2D array in c
[英]how to stop scanning when input is null (scan an unknown number of ints)
我目前正在開發一個程序,該程序掃描每個int並找出其是否完美。 問題是,我不知道輸入中有多少個整數,因此我想找出如何在輸入結束時停止掃描。
碼:
#include <stdio.h>
int main() {
int input[500], count;
for (count = 0; count < 500; count++) {
scanf("%d", &input[count]);
if (input[count] == 0)
break;
}
for (count = 0; count < 500; count++) {
if (findFactors(input[count]) % input[count] == 0)
printf("%d perfect\n", input[count]);
else if (findFactors(input[count]) % input[count] <= 2 ||
findFactors(input[count]) % input[count] >= input[count] - 2)
printf("%d almost perfect\n", input[count]);
else
printf("%d not perfect\n", input[count]);
}
}
在這種情況下,我需要輸入500個數字才能運行代碼。 當輸入為空時,我需要它運行。 我知道有“ / 0”之類的東西,但我不知道如何在此代碼中使用它。
使用函數時,請閱讀文檔
回報價值
這些函數返回成功匹配和分配的輸入項的數量,該數量可能少於所提供的數量,在早期匹配失敗的情況下甚至為零。
因此,您需要檢查scanf的返回值:
if (scanf("%d", &input[count]) != 1)
break;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.