2016-01-20 60 views
0

嘿所以我試圖從文本文件中讀取數字,並將它們放入數組中,但是當我嘗試打印它們時,我的數字已變得奇怪。文本文件看起來像:C從文件中讀取數字到數組

45 
77 
8 
... 

我猜有件事錯的循環I M使用,但我不能似乎發現了什麼。 感謝您的幫助!

代碼:

#define MAX_ARRAY_SIZE 20 

int main(int argc, char * argv[]) 
{ 
    FILE *myFile; 
    int myArray[MAX_ARRAY_SIZE]; 
    //char filename[32]; 
    //printf("enter filename\n"); 
    //scanf("%s", filename); 

    myFile = fopen("asdf.txt", "r"); 
    if (!myFile) { 
     printf("cant open file\n"); 
     return 1; 
    } 
    int status; 
    int i = 0; 
    while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) { 
     ++i; 
    } 
    fclose(myFile); 


    int a; 
    for (a = 0; i < MAX_ARRAY_SIZE; ++i) { 
     printf("%d ", myArray[i]); 
    } 
    printf("\n"); 
return 0; 
} 
+0

'for(a = 0; a BLUEPIXY

回答

0

的問題是在您的打印循環:

for (a = 0; i < MAX_ARRAY_SIZE; ++i) 

誰也不能保證你正在閱讀MAX_ARRAY_SIZE值。另外,如果你使用'a'作爲循環迭代器,那麼你需要使用'a'。你的循環應該是:

for (a = 0; a < i; ++a) 
    printf("%d ", myArray[a]); 

你也並不需要場寬度在格式說明符fscanf(myFile, " %d", &myArray[i]))會做。

+0

是啊:我以前使用「我」,並忘記將其全部更改爲:D thx – Nils

0

試試這個

while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) { 
    ++i; 
} 
0

真的......我還沒有看到打印循環代碼..對不起。 問題是在打印循環中不是fscan,請忽略我的回答

+0

您可以編輯您的答案以根據需要進行更改。不要提交其他答案。 –