2017-12-02 277 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