0

I'm implementing a code that takes values from a text file without knowing the number of values in the file. I have to ultimately output these values in another file with their average. I've added checks to see how much the code is running. It isn't reaching the third output namely "3.Here". I've tried changing the loop from while (!(input.eof())) to do while (//bool variable that keeps track of if it reaches end of file)

#include <iostream>
#include <fstream>
using namespace std; 

int main()
{
cout << "1.Here" << endl ; //first check to see output
ifstream input; 


input.open("input1.txt"); 
int numberofvalues = 0; 
cout << "2.Here" << endl ; //second check to see output. Its running till here

while(!(input.eof()))
{
 numberofvalues ++; 
}
cout << "3.Here" << endl ; //not running here

cout << "The numberofvalues: " << numberofvalues ; 
int arr[numberofvalues] ={}; 

for (int i=0; i<numberofvalues;i++)
{
int number; 
input >> number; 
arr[i] = number; 
}   

}
UKMonkey
  • 6,473
  • 3
  • 17
  • 29
Saad12
  • 1
  • 2
    Think about what you are doing with `while(!(input.eof())) { numberofvalues ++; }`. Do you do anything to cause input to become `EOF`? – NathanOliver Oct 15 '19 at 13:03
  • For future reference: C and C++ are not the same language; please don't tag C++ code as C. – UKMonkey Oct 15 '19 at 13:03
  • 1
    On a very related issue, please read [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) – Some programmer dude Oct 15 '19 at 13:05
  • 2
    `int arr[numberofvalues] ={};` is not valid C++. In C++, a `std::vector` is dynamic. A _variable length array_ is not standard C++. – Eljay Oct 15 '19 at 13:29

0 Answers0