0

I am trying to loop through a file containing the numbers 3.8, 2.1, 2.9, 3.1, 2.0, 1.6, 3.5, 2.3, 2.1, 3.7, and 3.2 and store them in an array. I then have to add those numbers and take the average of that. I have to use a while loop that loops until the end of file, but it is storing the wrong values in the array.

I have tried changing the order statements in the while loop, but it wont do anything. I have changed the file too and it did not help. I believe that it is in the while loop where it is messing up.


 subscript = 0;
 double gpasummer[subscript];
 fin >> gpa;

 while (!fin.eof())
 {
          gpasummer[subscript] = gpa;
          fin >> gpa;
          subscript = subscript +1;

 }

It should output the numbers in the file in the same order and then the average, but it only shows 3.8, 2.3, 2.3, 3.7, 3.2 and 0.0 (Which isnt even in the file), which makes the average wrong.

  • 3
    What do you think `double gpasummer[subscript];` does? – Beta Apr 04 '19 at 04:29
  • Declares an array with an index size that is equal to the subscript value? – user11309196 Apr 04 '19 at 04:31
  • 1
    Yes. And what is the subscript value at that time? – Beta Apr 04 '19 at 04:31
  • Zero, so the first value from the file is put into the array at index zero. Then it reads another value and increases the subscript size – user11309196 Apr 04 '19 at 04:34
  • 1
    Variable length arrays aren't valid C++. – Shawn Apr 04 '19 at 04:42
  • 1
    **No.** It declares an array of size zero, and writes values past the end of the array, causing Undefined Behavior. – Beta Apr 04 '19 at 04:48
  • Ohhhhhh ok. So what would be the best way to define the size of an array when you do not know how many values will be put in it? – user11309196 Apr 04 '19 at 04:50
  • 1
    Two approaches: 1) use a more sophisticated container, like `std::vector`, or 2) keep track of the size of the array and number of elements stored in it, and when you run out of space, resize it (i.e. declare a bigger array and copy the contents of the old array into the new one-- which basically demands dynamic allocation). – Beta Apr 04 '19 at 04:54
  • ok Thank you for the help! – user11309196 Apr 04 '19 at 05:04
  • 1
    Info about using `eof()`: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Galik Apr 04 '19 at 05:17

0 Answers0