[英]How to read structure information from an input file in 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;
}
您的代码看起来很好,所以我决定将其复制并查看出了什么问题。
在订单上确实做得很好,只需添加一些评论,这将是一项专业的工作。
请下次阅读有关如何编写问题的说明,并进一步解释问题所在。
在探讨结构问题之前,无论如何,第34行都会出现警告,该警告是:
scanf("%s", &filename);
格式指定类型为'char ',但参数的类型为'char( )[30]'
如果将其更改为:
scanf("%s", filename);
现在,据我了解,结构没有问题。
如果仅从以下位置更改打印:
for (j=0; j<MAP_SIZE*2; j++) {
至:
for (j=0; j<MAP_SIZE; j++) {
看起来很棒。
GL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.