0

I am trying to read double values from a text file and store them in a dynamic array of doubles. I have 4 double values in my file, each value in newline. I am using while loop to iterate through all the elements of m_numbers and storing a double value in them. while statement should fail after 4th iterations but it is doing 5 iterations. And that is resulting into wrong return value of the function. Also it seems like only first value is stored in all the elements.

double* m_numbers = nullptr;

int m_numCount = 4;

these variables are already initialized in header file.

file content:

6
12.2
3
34.1

bool Numbers::load()
   {
       int i = 0;
       if (m_numCount > 0) {
           delete[] m_numbers;
           m_numbers = new double[m_numCount+1];
           ifstream fin(m_filename);
           while (!fin.fail()) {
               fin >> m_numbers[i];
               i++;
           }
       }
       return i == m_numCount;
   }
  • *these variables are already initialized in header file.* is probably a bad idea. Definitions of data in a header almost always lead to violation of the [One Definition Rule](https://en.cppreference.com/w/cpp/language/definition#One_Definition_Rule) – user4581301 Nov 07 '20 at 01:13
  • 2
    `while (!fin.fail())` tests for failure BEFORE reading, not after. Since read number four was successful there's nothing to stop the program from spinning around, passing the test in the `while` loop and then failing `fin >> m_numbers[i];` unchecked, leaving you with a bogus fifth value. Use `while (fin >> m_numbers[i])` instead. Read and test. If good enter loop. – user4581301 Nov 07 '20 at 01:16
  • What you have is a variant of [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) but I'm not sure it's close enough to dupe-hammer the question closed. – user4581301 Nov 07 '20 at 01:18
  • @user4581301 the loop is working fine now but it is still storing 1st value in all elements of m_numbers. – Mandeep Kumar Nov 07 '20 at 01:46

0 Answers0