2017-12-02 251 views
0

我想將輸入文件中的數據存儲到結構中,但我不確定我在做什麼錯誤。 這是輸入文件。如何從輸入文件中讀取結構信息c

4 2  1 1  3 1 

1 1  2 1  3 1 

1 1  5 3  1 1 

每個的第一個數字應該存儲爲沙,第二個數字應該存儲爲寶。

這是到目前爲止我的代碼:

#include <stdio.h> 
#include <string.h> 

#define PIRATES 
#define MAP_SIZE 3 

//structures 
struct pirate { 
    int dig; 
    int carry; 
}; 

struct map { 
    int sand; 
    int treasure; 
}; 


//functions 
int hours_crew(); 
void scan_file(); 

//main function 
int main() { 
    FILE * ifp = NULL; 
    struct map map[MAP_SIZE][MAP_SIZE]; 
    int i, j; 
    char filename[30]; 

    printf("You have arrived at Treasure Island!\n"); 

    while (ifp == NULL) { 
     printf("What is the name of your map?\n"); 
     scanf("%s", &filename); 

     ifp = fopen(filename, "r"); 
    } 

    for(i=0; i<MAP_SIZE; i++) { 
     for (j=0; j<MAP_SIZE; j++) { 
      fscanf(ifp, "%d", &map[i][j].sand); 
      fscanf(ifp, "%d", &map[i][j].treasure); 
     } 
    } 

    for(i=0; i<MAP_SIZE; i++) { 
     for (j=0; j<MAP_SIZE*2; j++) { 
      printf("%d", map[i][j].sand); 
      printf("%d\n", map[i][j].treasure); 
     } 
    } 


    fclose(ifp); 
    return 0; 
} 
+3

'爲(J = 0;Ĵ

+0

是的。謝謝! – Momo

+0

改進的格式 –

回答

0

你的代碼看起來這麼好,所以我決定把它複製,看看哪裏出了問題。

訂單真的很好,只需添加一些評論,這將是一個專業的工作。

請稍後閱讀關於how to write a question的說明並解釋更多問題。

之前要在與所述結構中的問題的任何方式,有上來在線路34上發出警告,其是:

scanf("%s", &filename); 

格式指定類型「炭」,但該參數的類型爲'炭()[30]」

如果它更改爲它可以容易地固定:

scanf("%s", filename); 

現在,據我瞭解,結構沒有問題。

如果你只是從改變印刷:

for (j=0; j<MAP_SIZE*2; j++) { 

到:

for (j=0; j<MAP_SIZE; j++) { 

它看起來那麼美好。

GL