如何将指针值读入结构数组

How to read pointer values into an array of structs

我有以下结构

typedef struct
{
    char* city;
    int temp;
} Place;`

我正在尝试将一行中的两个值读入结构数组。

这些行看起来像:

Los Angeles; 88

我正在尝试将数据读入数组。假设我的内存分配是正确的,那么读取这些值的正确方法是什么。

我的代码

    void readData(FILE** fpData, FILE** fpOutput)
{
    char s[100];
    int index = 0;

    Place *values;
    values=malloc(size * sizeof(Place));
    if (values == NULL)
    {
        MEM_ERROR;
        exit(1);
    }


    for (int a = 0; a < size; a++)
    {
        (values[a]).city = (char *) malloc(100 * sizeof(char));
        if(values[a].city == NULL)
        {
            MEM_ERROR;
            exit(100);
        }
    }

    while(fgets(s, sizeof(s), *fpData)!=NULL)
    {
        sscanf(s, "%[^:]%*c%d\n", values[index].city, &values[index].temp);
        index++;
    }

    sortInsertion(values, size, fpOutput);

    free(values);
    return;
}

城市没有进入数组,所以我假设它说 values[index].city 的部分是不正确的。

我该如何解决这个问题?

您的数据使用分号 ; 而您的 sscanf 格式使用冒号 :,请确保这是相同的字符。如果你的数据确实使用了分号,将sscanf格式中的%[^:]部分改为%[^;]

这是我的代码以及我如何 运行 向您展示它的工作原理:

#include <stdio.h>

struct Place {
    char city[100];
    int  temp;
} values[30];

int main() {
    char s[100];
    int i=0, n=0;
    while ( fgets(s, sizeof(s), stdin) != NULL ) {
        sscanf(s, "%[^;]%*c%d\n", values[n].city, &values[n].temp);
        n++;
    }
    printf("n=%d\n", n);

    for ( i=0; i<n; i++ ) {
        printf("values[%d] = (%s, %d)\n", i, values[i].city, values[i].temp);
    }
}

这就是我 运行 在 Linux 上的做法:

% for a in `seq 1 3`; do echo "City-$a; $a$a"; done | ./a.out 
n=3
values[0] = (City-1, 11)
values[1] = (City-2, 22)
values[2] = (City-3, 33)
sscanf(s, "%[^:]%*c%d\n", values[index].city, &values[index].temp);

这会将读取的行开头到第一个冒号 (:) 的所有内容复制到您分配的 city 数组中。您的示例输入似乎有一个分号 (;),因此您将在 city 数组中得到整行,而在 temp 字段中没有任何内容。

您不进行任何输入检查,因此任何太长的输入行都会被分成多个(可能已损坏)城市。如果文件中不完全 size 行,你也会遇到问题,因为你不检查以确保 index 在阅读时没有超过 size,并且你假设你最后有 size 个条目而没有检查。