简体   繁体   English

将值从文件存储到 C 中的结构数组

[英]Storing values from file to struct array in C

I am trying to read values from my text file and store them in struct array.我试图从我的文本文件中读取值并将它们存储在结构数组中。 My text file has these values:我的文本文件具有以下值:

names.txt名称.txt

Num_of_rec: 5
3 7 10 1 red
5 6 8 2 red
9 9 16 5 blue
13 4 19 2 green
12 8 15 4 blue

And my code so far is this:到目前为止我的代码是这样的:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ERROR -1
#define MAXLEN 256

struct Point {
    float x;
    float y;
};

struct Rectangle {
    struct Point top_left;
    struct Point bottom_right;
    char color[7];
};


int main() {
    int i, N;
    char junk[MAXLEN];
    struct Rectangle *data;
    FILE  *fp;

    fp = fopen("names.txt", "r");

    fscanf(fp,"%s %d\n",junk,&N);
    printf("No: %d", N);

    data = (struct Rectangle *) malloc(N*sizeof(struct Rectangle));

    for(i=0; i<N; i++) {
        fscanf(fp, "%lf %lf %lf %lf %s", data[i].top_left.x, data[i].top_left.y, data[i].bottom_right.x, data[i].bottom_right.y);
    }

    return 0;
}

I want to add all these values in a struct array(data), but I don't know how to do this properly.我想将所有这些值添加到结构数组(数据)中,但我不知道如何正确执行此操作。 Until now the output is:到目前为止,输出是:

No: 5

and it just crash.它只是崩溃。 I don't understand if the problem is the method that I am using to read the values from the file and store them to the struct array, or something else.我不明白问题是我用来从文件中读取值并将它们存储到结构数组的方法还是其他方法。

fscanf(fp, "%lf %lf %lf %lf %s", data[i].top_left.x, data[i].top_left.y, data[i].bottom_right.x, data[i].bottom_right.y);

There are three problems regarding fscanf : fscanf存在三个问题:

  1. fscanf takes pointers, you pass in values fscanf 接受指针,您传入值
  2. fscanf expects 5 pointers, you only provide 4 values. fscanf 需要 5 个指针,您只提供 4 个值。
  3. format specifier %lf expects a pointer to a double type格式说明符%lf需要一个指向double类型的指针

Changing the above statement to the follow should solve the crash.将上述语句更改为以下语句应该可以解决崩溃问题。

fscanf(fp, "%f %f %f %f %s", &data[i].top_left.x, &data[i].top_left.y, &data[i].bottom_right.x, &data[i].bottom_right.y, data[i].color);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM