2017-04-14 43 views
2

我有一個文件,我必須讀取一些數字並將它們放入數組中。唯一的問題是我不知道如何找到它的大小。我給了數組的最大大小,但數字不能完全填充數組。我嘗試了許多不同的方法來使其工作,但它並沒有從文件中讀取正確的值。有沒有其他的方式來做到這一點沒有sizeof?從文件中檢索數組並找到它的大小C

#include<stdio.h> 

#define MAX_NUMBER 25 
int main(void) 
{ 
int test[]; 
int size; 

FILE* sp_input;  
int i; 
sp_input = fopen("a20.dat", "r"); 

if (sp_input == NULL) 
    printf("\nUnable to open the file a20.dat\n"); 
else 
    { 
    while(fscanf(sp_input, "%d", &test[i])!=EOF) 
    { 
    size=sizeof(test)/sizeof(test[0]); 
    } 

    for(i = 0; i < size; i++) 

    printf("\na[%d]=%d has a size of %d\n", i,test[i],size); 
    fclose(sp_input);  
    } 

    return 0; 
} 
+0

「i」未初始化,永遠不會改變while循環中的值。 –

+0

如果'size'應該是數組中有多少個數字,那麼爲什麼不從0開始併爲每個讀取的數字增加? – Dmitri

+0

此外,您還需要給出'test'的元素數量,例如。 'int test [MAX_NUMBER];' - 該數組總是會有最大數量的元素,但是您可以通過'size'跟蹤您實際使用的元素數量。 – Dmitri

回答

2

如果你每次成功地做了fscanf時間增加i,它將作爲項目閱讀次數的計數。

i = 0; 

while (fscanf(sp_input, "%d", &test[i]) == 1) { 
    i = i + 1; 
} 

// Now, i is the number of items in the list, and test[0] .. test[i-1] 
// are the items. 

編輯:作爲@chux指出,在這種情況下,最好到比較1,項目的預期數量進行掃描,在每次調用。如果提供虛假輸入(非數字),仍然存在問題,您應該停止。

+1

較小的'fscanf(sp_input,「%d」,&test [i])== 1'更習慣於循環,只要結果如預期的那樣她比其他可能的'fscanf()'結果中的1個要好。當然在這種情況下,預期只有'EOF'或1,但這個公理適用於更復雜的掃描。 – chux

1

定義最大大小數組並繼續循環。

文件輸入不需要填充該數組,只是填充它,因爲它可以。保持跟蹤i,使用了多少個test[],並確保不要過度填充陣列。

#define MAX_NUMBER 25 
int test[MAX_NUMBER]; 

FILE* sp_input = fopen("a20.dat", "r"); 
... 

// Use `size_t` for array indexing  
size_t i; 
// do not read too many `int`  
for (i=0; i<MAX_NUMBER; i++) { 
    if (fscanf(sp_input, "%d", &test[i]) != 1) { 
    break; 
    } 
    printf("test[%zu]=%d\n", i, test[i]); 
}