![](/img/trans.png)
[英]How to read numbers into an array without specifying the array size in C language
[英]How read two lines numbers from input to 2 arrays, C language? Without knowing the amount of number? in C
例如,輸入為:
12 23 32 41 45
22 11 43
行以'\\n'
結尾,
我想將數字保存到a[]
和b[]
;
a[] = {12, 23, 32, 41, 45}
b[] = {22, 11, 43}
關鍵是我不知道每行多少個。
如果我知道line1 n
數字和line2 m
數字,我將使用“ for循環”,這是毫無疑問的。
就像,
for(int i = 0; i < n; i++) scanf("%d", a+i);
for(int i = 0; i < m; i++) scanf("%d", b+i);
但是,我不知道n和m,怎么辦,伙計們?
如果您想繼續使用scanf方法,我建議使用否定的scanset %[^]
格式說明符。
scanf("%[^\\n]", pointerToCharArray)
它應該讀取不限數量的字符, 但不包括指定的字符(在我們的示例中為換行符)。 如果您想放棄換行符,請按以下方式閱讀:
scanf("%[^\\n]\\n", pointerToCharArray)
可以在下面找到參考頁面的鏈接。 否定的掃描集說明符包括在列表中:
http://www.cplusplus.com/reference/cstdio/scanf/
從這一點出發,使用strtok()將scanf的輸出標記為數字數組是一件簡單的事情。 如果您不熟悉strtok,則在下面提供另一個參考鏈接:
http://www.cplusplus.com/reference/cstring/strtok/
我希望這有幫助!
讓我們使用非標准的getline
,這是一個常見的庫擴展。 @Abbott將整行讀到分配的內存中。
如果需要一個數組並在運行時確定其大小,請使用C99和C11(可選)中提供的可變長度數組 。
創建一個函數進行計數並保存數字。 使用strto...()
函數進行健壯的解析。
size_t count_longs(char *line, long *dest) {
size_t count = 0;
char *s = line;
for (;;) {
char *endptr;
long num = strtol(s, &endptr, 10);
if (s == endptr) {
break; /// no conversion
}
s = endptr;
if (dest) {
dest[count] = num;
}
count++;
}
return count;
}
示例代碼段
char *line = NULL;
size_t len = 0;
ssize_t nread = getline(&line, &len, stdin); // read the whole line
if (nread != -1) {
// successful read
long a[count_longs(line, NULL)]; // determine array size and use a
count_longs(line, a); // 2nd pass: assign array elements.
nread = getline(&line, &len, stdin);
if (nread != -1) {
// successful read
long b[count_longs(line, NULL)];
count_longs(line, b);
// Do something with a and b
}
}
free(line);
len = 0;
下面的代碼可能會滿足OP的要求。 該解決方案讀取未指定數量的整數並將其存儲在arr
。 要中斷循環/結束輸入,只需輸入一個非整數值即可。 可以進一步指定搜索特定的輸入等。
int c = 0;
int *arr = NULL;
int *extArr = NULL;
int i = 0;
for (i = 0; scanf("%d", &c) == 1; i++)
{
extArr = (int*)realloc(arr, (i+1) * sizeof(int));
arr = extArr;
arr[i] = c;
}
free(arr);
但是,我個人會在我提供的解決方案和armitus答案之間混合使用(如果我不能使用getline
或類似方法),因為為每個int值重新分配內存對我來說似乎是多余的。
編輯由於存在關於我提供的代碼以及如何最好地使用它來滿足OP的問題的一些問題。 代碼片段應該展示如何為未指定數量的整數輸入創建自己的scanf樣式函數,一次讀取一個完整的數組(在這種情況下,必須省略free()
,直到對數組進行一次處理(顯然)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.