我想將值(浮點數)讀入數組,但我不知道數值。C scanf - 未知數組大小
我的輸入是這樣的
Enter values: 1.24 4.25 1.87 3.45 .... etc
我怎麼能這個輸入加載到一個數組中?我知道當輸入0或EOF時輸入結束。
while(0 or EOF){
scanf("%f", &variable[i])
i++;
}
謝謝。當它試圖
我想將值(浮點數)讀入數組,但我不知道數值。C scanf - 未知數組大小
我的輸入是這樣的
Enter values: 1.24 4.25 1.87 3.45 .... etc
我怎麼能這個輸入加載到一個數組中?我知道當輸入0或EOF時輸入結束。
while(0 or EOF){
scanf("%f", &variable[i])
i++;
}
謝謝。當它試圖
您可以動態分配數組,然後在先前分配的緩衝區已滿時爲其重新分配內存。請注意,格式字符串爲scanf
的轉換說明符%f
會讀取並放棄前導空格字符。從scanf
手冊頁 -
scanf
返回成功匹配和分配 項目可以是在 早期匹配失敗的情況下少於所提供,甚至是零數。 如果在第一次成功轉換或發生匹配 故障之前達到輸入 的末尾,則會返回值EOF。
這意味着scanf
返回EOF
只有當它遇到EOF
當它被調用,因爲EOF
必須以新行'\n'
前面否則將無法正常工作(視操作系統而定)的第一個輸入。這裏有一個小程序來演示如何做到這一點。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t len = 4;
float *buf = malloc(len * sizeof *buf);
if(buf == NULL) { // check for NULL
printf("Not enough memory to allocate.\n");
return 1;
}
size_t i = 0;
float *temp; // to save buf in case realloc fails
// read until EOF or matching failure occurs
// signal the end of input(EOF) by pressing Ctrl+D on *nix
// and Ctrl+Z on Windows systems
while(scanf("%f", buf+i) == 1) {
i++;
if(i == len) { // buf is full
temp = buf;
len *= 2;
buf = realloc(buf, len * sizeof *buf); // reallocate buf
if(buf == NULL) {
printf("Not enough memory to reallocate.\n");
buf = temp;
break;
}
}
}
if(i == 0) {
printf("No input read\n");
return 1;
}
// process buf
for(size_t j = 0; j < i; j++) {
printf("%.2f ", buf[j]);
// do stuff with buff[j]
}
free(buf);
buf = NULL;
return 0;
}
+1這是最好的答案。 – dureuill
我想你的實際擔憂是用戶將要輸入的未知浮點數。你可以使用指針浮動,做一些預定義大小的malloc,如果你的限制已經達到了,然後做一個realloc來增加內存。在進行反應時,您需要處理以前接受的數據。
您需要動態分配數組,因爲在編譯時您不知道它的大小。
// INITIAL_SIZE can be the average expected size of your array
#define INITIAL_SIZE 4
// size will track the current maximum size of youe array.
size_t size = INITIAL_SIZE;
// dynamic allocation for variable
float* variable = malloc(sizeof(float)*size);
// check that the allocation happened correctly
assert(variable != NULL);
// i contains the current actual size of your array
int i = 0;
while (0 or EOF) {
if (i >= size) {
// if the array is getting bigger than its max size, resize it.
size *= 2;
// This will reallocate enough memory for variable.
variable = realloc(variable, sizeof(float)*size);
// check that the allocation happened correctly;
assert(variable != NULL);
// (NB: It IS important to affect variable to the result of
// realloc, you can't simply realloc as in some cases the
// original pointer will become invalid!)
}
scanf("%f", &variable[i])
i++;
}
另外請注意,variable
不是一個很好的變量名稱。使用描述你的變量用於的名稱。
EDIT:校正後的尺寸的realloc到ALLOC size*2
漂浮並避免它可怕斷裂,作爲展開指出。
發佈的僞代碼的哪部分不起作用? – Lundin