I hope this question isn't too similar to another that's posted. I am still learning how to read other peoples code at this point let alone write my own. I am confused as to how to read both a string and int from a line in a file and store it in a struct called People. I have been looking at fgets, fscanf and even fread but I can't figure out what to use and where to use it. I am getting this data from a file with a max of 10 entries that looks like this:
Joshua 50
Dwayne 90
Jennifer 45
Goldilocks 85
Here is my code:
typedef struct
{
char *name[20];
int change_amount;
int fifties;
int twenties;
int tens;
int fives;
}People;
int get_file()
{
const int MAXPEOPLE = 10;
People persons[MAXPEOPLE];
int i = 0;
FILE *fpointer;
char line[12];
fopen("file.txt", "r");
if (fpointer == NULL)
{
perror("Error opening file");
return (0);
}
while (fgets(line, 8, fpointer) != NULL)
{
//Max number of letters for name under assumption is 8
char name[8];
int amount = 0;
scanf(line, "%s %d", name, amount);
printf("%s", name);
memset(line, 0, 8);
for (int i = 0; i < MAXPEOPLE; ++i)
{
return(0);
}
}
}
Any help is appreciated. Go easy on me :)
sscanf()andscanf(), are you? Seems like you read intolinewithfgets()(wise move) and then try to scan from there, but use the wrong function to do so.fopen()but don't assign (or check) the returned value. You then test the still uninitializedfpointer. Not a recipe for happiness!