cscanfinfo

How to scan info from .txt to array of structures?


I have such info in info.txt:

KHNU 300 12 24
SHEVCHENKA 500 15 32
KPI 900 13 35
GORSKOGO 645 14 45

All I need is to write these info to array of structures, but as newbie I can't understand how to do it. Here's the code:

void readFile(FILE* pf);
struct University
{
    char name[30];
    int quantityOfStudents;
    int quantityOfFaculties;
    int quantityOfDepartments;
};

int main()
{
    FILE* pf = fopen("info.txt", "rb");

    readFile(pf);
    system("pause");
    return 1;
}

void readFile(FILE* pf)
{
    if ((pf == NULL)) { printf("Error!"); exit(1); }

    struct University *u[4] = malloc(4 * sizeof(struct University));

    for (int i = 0; i < 4; i++)
    {
        fscanf(pf, "%s %d %d %d", &u[i]->name, &u[i]->quantityOfStudents, &u[i]->quantityOfFaculties, &u[i]->quantityOfDepartments);
    }
}

But, as you probably guessed, it does not scan.

Please, let just know the algorithm how to scan info from .txt to array of structures!

Thanks.


Solution

  • I think your code has some compilation problems. You should be able to find them while compiling your code. I tried fixing them and was able to get your code working by fixing these:

    1. malloc returns pointer to allocated memory not array of pointers. So your struct allocating statement which is this:
    struct University *u[4] = malloc(4 * sizeof(struct University));
    

    should look like this:

    struct University *u = (struct University *)malloc(4 * sizeof(struct University));
    
    1. When you're scanning file contents into struct array; you access struct array using u[i] and use -> for getting struct elements. But u[i] resolves to struct University not struct University *. I think it should look like this instead:
    for (int i = 0; i < 4; i++)
    {
        fscanf(pf, "%s %d %d %d", &u[i].name, &u[i].quantityOfStudents, &u[i].quantityOfFaculties, &u[i].quantityOfDepartments);
    }