简体   繁体   中英

Reading string and integer from file into struct - C

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:)

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

Ie 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!

Ie this

fopen("file.txt", "r");
if (fpointer == NULL)

should be

fpointer = fopen("file.txt", "r");
if (fpointer == NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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