Reputation: 1
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 :)
Upvotes: 0
Views: 901
Reputation: 26783
I think the main issue with getting the scanning right is that you read into line with fgets()
(wise move) and then try to scan from there.
scanf(line, "%s %d", name, amount);
but use the wrong function to do so. Use sscanf()
.
https://en.cppreference.com/w/c/io/fscanf
For completeness let me add the contribution from comments by Martin James and Jonathan Leffler:
You only live twice, but you can only return once: your loop is pointless
I.e. once any iteration of your for
loop has a return
, and all of them have, your while
loop is finished.
You call fopen() but don't assign (or check) the returned value. You then test the still uninitialized fpointer. Not a recipe for happiness!
I.e. this
fopen("file.txt", "r");
if (fpointer == NULL)
should be
fpointer = fopen("file.txt", "r");
if (fpointer == NULL)
Upvotes: 1