【问题标题】:How to read structure information from an input file in c如何从c中的输入文件中读取结构信息
【发布时间】:2018-05-16 15:57:36
【问题描述】:

我正在尝试将输入文件中的数据存储到结构中,但我不确定我做错了什么。 这是输入文件。

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;
}

【问题讨论】:

  • for (j=0; j&lt;MAP_SIZE*2; j++) { 在您的显示循环中...这是错误。那是你的问题吗? (你没有描述你的问题)
  • 是的。谢谢!
  • 改进格式

标签: c arrays file input structure


【解决方案1】:

你的代码看起来很漂亮,所以我决定复制它,看看哪里出了问题。

订单做得很好,只需添加一些评论,这将是一项专业的工作。

请下次阅读有关how to write a question 的说明并详细说明问题所在。

在解决结构问题之前,第 34 行会出现警告:

scanf("%s", &filename);

format 指定类型 'char ' 但参数的类型为 'char ()[30]'

如果您将其更改为以下内容,则可以轻松修复:

scanf("%s", filename);

现在,据我了解,结构没有问题。

如果您只是将打印更改为:

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

到:

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

它看起来很棒。

GL

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多