简体   繁体   中英

Why does fscanf only read the first word of one string from file

I have a problem when I try to read the file information for my struct with fscanf() . It just reads the first line of the string and the loop never ends. How can I solve the problem?

Struct

typedef struct {
    int id;
    char name[80];
    char nameStadium[80];
    int numberPlacesStadium;
    float funds;
    float monthlyExpenses;
    int active;
} Team;

And I use this code to read

void showAll(void)
{
    FILE* file;
    Team team;

    file = fopen("file.txt", "rt");

    if (file == NULL)
    {
        printf("!!!Cant open file!!!\n");
        return;
    }

    rewind(file);

    printf("\n\n=== TEAMS ======\n");
    printf("%s\t%s\n", "ID", "NAME");

    while (fscanf(file, "%6d %s %s %6d %f %f %03d\n", &team.id, team.name, team.nameStadium, &team.numberPlacesStadium, &team.funds, &team.monthlyExpenses, &team.active) != EOF)
    {
        if (team.active != 0)
        {
            printf("%d\t%s\n", team.id, team.name);
        }
    }

    fclose(file);

}

I can't understand why fscanf() just gets the first word and not the full string

Does anyone know how to solve this?

I just tested out your code with a sample text file I made following the format you posted. Everything is read in and seems to be fine except that you didn't properly close the file. It should look like this.

fclose(file);

If you want your code to be able to read in strings with spaces, your best bet is to use a delimiter system. The code below reads for their type (assuming the integers won't have spaces in-between them), reads for a sequence of 80 characters that aren't commas (which will be the names), and then proceeds with the other numbers separated by commas.

  while (fscanf(file, "%d, %80[^,], %80[^,], %d, %f, %f, %d\n", &team.id, 
     team.name, team.nameStadium, &team.numberPlacesStadium, &team.funds, 
    &team.monthlyExpenses, &team.active) != EOF) 
  {
      if (team.active != 0)
    {
        printf("%d\t%s %s\n", team.id, team.name, team.nameStadium);
    }
  }

I've tested it to work and it does, but keep in mind this also isn't the most elegant solution.

These are what the rows in my text file looks like:

 133222, Bears, Bears Stadium, 444333, 23, 35.3, 52
 666222, Eagles, Eagles Stadium, 322222, 13, 56.3, 54

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