-1

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Alex
  • 3
  • 3
  • 2
    Does it compile at all? `struct University *u[4] = malloc(4 * sizeof(struct University));` looks very wrong. Also you don't do anything with `u` afterwards, so how can you claim it "doesn't scan"? – Eugene Sh. Mar 04 '21 at 16:26
  • @Eugene Sh. It does not compile... – Alex Mar 04 '21 at 16:27
  • 1
    Then it is not that it is not scanning, but it is not compiling. First thing make it compile by fixing the errors one by one. – Eugene Sh. Mar 04 '21 at 16:33
  • It looks like you already have the algorithm to read the file (read the values in a loop). Now you need to fix your code. – Thomas Sablik Mar 04 '21 at 16:54

1 Answers1

0

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);
}
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40