c - 如何将文件中的字符串和 float 存储到结构中?

标签 c cs50 strtok

我正在尝试将字符串和 float 从文件存储到结构中。我已成功将 float 存储到结构中,但字符串的工作方式不同。

我的文件看起来像这样

Names                 weight(kg)
John Smith            56.5
Joe                   59.75
Jose                  60.0

输出:

Jose                  56.5
Jose                  59.75
Jose                  60.0

这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<cs50.h>
#include<string.h>

typedef struct
{
    string name;
    float weight;

}People;

int main(void)
{
    FILE *fp1;
    fp1 = fopen("file.txt","r");

    people person[255];

    if(!fp1)
    {
        printf("ERROR OPENING FILE");
        exit(1);
    }
    else
    {
        // store names and weights in person.name and person.weight from file 1
        get_nameAndWeight(fp1 ,person);
        for (int i = 0; i < 6; i++)
        {
            printf("%s\t%.2f\n",person[i].name, person[i].weight);
        }
    }

}

void get_nameAndWeight(FILE *fp, people array[])
{
    char cur_line[255], *token;
    float weight;
    int i = 0;

    while(!feof(fp))
    {
        fgets(cur_line, sizeof(cur_line), fp);
        if(i == 0)
        {
            i++;
        }
        else
        {
            token = strtok(cur_line, "\t\n ");
            while (token != NULL)
            {
                if(atof(token) != 0)
                {
                    array[i-1].weight = atof(token);
                }

                else
                {
                    array[i].name = token;
                }
                token = strtok(NULL, "\t\n ");
            }
            i++;
        }
    }
}


我的代码有什么问题吗?还有其他方法可以做到这一点吗?

最佳答案

请注意,strtok 不会分配任何新内存,它会修改您传入的数组。因此,所有对象都指向同一个数组 cur_line

您应该为 strdup() 的名称分配新的内存或一些类似的功能。像这样的东西:

array[i].name = strdup(token);

关于c - 如何将文件中的字符串和 float 存储到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65640072/

相关文章:

c - 如何保存字符串标记,将其内容保存到数组中,然后使用这些内容进行进一步比较

c - strtok() 对于解析句点但保留句点有用吗? (C)

无论我更改什么,C 程序都输出相同的数字

c - 使用 Visual Studio 和 Openssl 进行 AES 256 CTR 加密/解密

C:函数在单独的实例中以不同的方式运行

c - 我的 recovery.c 代码正确恢复 jpeg,但未通过 cs50 检查

C if 语句,检查特殊字符和字母的最佳方法

c++ - 设置非常简单的 C/C++ 链接问题

C 程序打印数字、星号和连字符的梯形图案

c - 使用 strtok 替换输入文件 C 中的部分字符串