2

Im trying to store string and floats from a file to a struct. I have managed to store floats to the struct, but the strings won't work the same.

my file looks like this

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

output:

Jose                  56.5
Jose                  59.75
Jose                  60.0

and here is my code:

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


What is wrong with my code? Is there another way to do this?

user3386109
  • 34,287
  • 7
  • 49
  • 68
Mark
  • 21
  • 3

2 Answers2

3

Note that strtok does not allocate any new memory, it modifies the array you passed in. So all of your objects are pointing to the same array cur_line.

You should allocate new memory for the names with strdup() or some similar function. Something like:

array[i].name = strdup(token);
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
1

You should use strcpy for example !

You cannot just assign a string to a variable in c. You need to copy each char of the source to your destination string.

I guess strtok return a char*, so this char* is your source and name is your destination. Check strcpy manual.

I guess your following cs50 classes, so you don't have to deal with allocation if i remember well. Still, it would relevant to check malloc and strdup function for you next exercices ;)

UnDesSix
  • 68
  • 1
  • 1
  • 8