繁体   English   中英

如何将字符串和浮点数从文件存储到结构?

[英]how to store string and float from a file to a struct?

我试图将字符串和浮点数从文件存储到结构。 我已经设法将浮点数存储到结构中,但字符串的工作方式不同。

我的文件看起来像这样

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

output:

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 不会分配任何新的 memory,它会修改您传入的数组。因此,您的所有对象都指向同一个数组cur_line

您应该为带有strdup()或类似 function 的名称分配新的 memory。 就像是:

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

例如,您应该使用 strcpy !

您不能只将字符串分配给 c 中的变量。 您需要将源的每个字符复制到目标字符串。

我猜 strtok 返回一个 char*,所以这个 char* 是你的来源,名字是你的目的地。 检查 strcpy 手册。

我猜你下面的 cs50 课程,所以如果我没记错的话,你不必处理分配问题。 不过,在接下来的练习中检查 malloc 和 strdup function 还是很重要的;)

暂无
暂无

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

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