0

I'm stuck at this where I need to find the highest average number inside a text file with an unknown amount of data. The data inside the txt is like this

id group score

2203 1 33
5123 2 58
3323 3 92
5542 2 86
....
....

and the file keeps going.

I'm currently trying to create a struct and then store the values inside of it, but I cannot determine the size of struct since the file has unknown amount of data and it might change every run.

What I tried is this

  while(!feof(fptr)) {
    for(i = 0; i < sizeoffile; i++ ) { // here i should add the size or the amount of data.
    fscanf(fptr,"%d %d %d",&p[i].num, &p[i].grp, &p[i].score);
    }
  }

I tried adding a counter inside the while loop to get the amount of data but it doesn't work. Im not sure if i need to use malloc or something else.

Example run: code read the following file

1312 1 30
1234 1 54
2931 2 23
2394 2 99
9545 3 95
8312 3 100
8542 4 70
2341 4 56
1233 1 70
2323 1 58

output

group 3 has the highest average of 97
MohmedBm
  • 31
  • 6
  • To calculate an average you need to keep a grand total, and the number of values. The average is the one divided by the other. No need to make it complicated. – Cheatah Jan 10 '22 at 18:16
  • 1
    MohmedBm, Who or what text suggested `while(!feof(fptr)) {`? – chux - Reinstate Monica Jan 10 '22 at 18:17
  • @Cheatah Yes i can get the average of the entire file easily, but I need to get which group has the highest average and keep count of that. – MohmedBm Jan 10 '22 at 18:20
  • @chux-ReinstateMonica I was taught that i can read a file of unknown length using that. What I understand is that it runs until the end of file. is that correct? – MohmedBm Jan 10 '22 at 18:21
  • 2
    MohmedBm, it is not. See [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). Code should test the return value of `fscanf()` instead. Still this is not the main problem. – chux - Reinstate Monica Jan 10 '22 at 18:23
  • Well I don't understand your problem. Why don't you show a few sample inputs and desired outputs? – Cheatah Jan 10 '22 at 18:23
  • Sorry to bother you, i added an example. – MohmedBm Jan 10 '22 at 18:36

1 Answers1

2

Code could go through the file once and determine the count of records: N and then read again, this time saving in an array of size N.

Alternative, use a linked-list.

or allocated some memory and re-allocate as needed.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • I'm sorry, but im a bit confused. how can I exactly run through the file once without using the `while(feof())`? – MohmedBm Jan 10 '22 at 18:35
  • 1
    @MohmedBm [Already answered](https://stackoverflow.com/questions/70657057/assigning-values-to-a-struct-from-text-file-with-unkown-amount-of-data/70657305?noredirect=1#comment124906979_70657057). " test the return value of `fscanf()`". – chux - Reinstate Monica Jan 10 '22 at 18:36