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?