I have this simple input data file:
1 2
2 3
I'm reading it using the following program:
#include<cassert>
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
double y[10];
double z[10];
std::ifstream read_file("input.dat");
assert (read_file.is_open());
int i=0;
while(!read_file.eof())
{
read_file >> y[i] >> z[i];
std::cout<<"y["<<i<<"] = " << y[i] << " z["<<i<<"] = " << z[i]<<"\n";
i++;
}
read_file.close();
return 0;
}
after executing the code, I got the following output:
y[0] = 1 z[0] = 2
y[1] = 2 z[1] = 3
y[2] = -1.6995e-41 z[2] = 1.52064e-314
So, the issue here that it reads an additional row of data that does not actually exist in the input file. Note that the problem is not related to the above declared array sizes y[10], z[10] ... I know that the problem is solved if I use a for loop instead. The advantage of this while loop is that it does not need to know the exact number of lines present in the input file; still I need to declare the array y and z sizes to be larger than the actual number of lines.
Any hint to get rid of the last-unwanted-line-of-data?
Please stick to the while(!read_file.eof())
form.