May 5th, 2011, 05:43 PM
EOF() function is re-reading a line of data
I have to write a program to calculate the least squares line from a set of data. I named the file "data.txt" and these are the contents:
and this is my program so far:
I havent calculated the line yet, I am stuck with reading the data from the file. From what I've read, I gathered that eof() doesn't become true until it reads past the end of the file. I read that you should use the get() function to force the program into reading the next line, triggering the eof to switch, but no matter which was I organize my while loop, I can't get it to run properly. I end up with 6 data points instead of five, the extra data point is the last data point which is re-entered into the algebra, giving me incorrect data.
using namespace std;
int numpoints = 0;
double x=0, y=0, sumx=0, avgx=0, sumy=0, avgy=0, sumxy=0, sumxsquared=0, sumysquared=0;
double m=0, b=0, r=0, first=0,second=0,third=0,fourth=0;
cout << "There was an error opening the file.\n";
while (! inStream.eof())
inStream >> x >> y;
sumx += x;
sumy += y;
sumxy += (x*y);
sumxsquared += (x*x);
sumysquared += (y*y);
cout << "Sum X=" << sumx <<"\n"
<< "Sum Y=" << sumy <<"\n"
<< "Sum XY=" << sumxy <<"\n"
<< "Sum X^2=" << sumxsquared <<"\n"
<< "Sum Y^2=" << sumysquared <<"\n"
<< "Number of points=" << numpoints << "\n";
May 6th, 2011, 05:32 AM
Re: EOF() function is re-reading a line of data
As you say, the problem with eof is that of not neccessarilly trigered until you have read past the end of a file. In particular, it can create problems with files with new lines at the end, eg:
In the first case, the file has been read, up to, but not including, EOF.
The usually accepted solution to this problem is rather than scan for eof, just read your input as you normally would, until it fails. then, you check you are indeed and eof.
You can also read Parashift's input/output FAQ.
const std::string my_string_file1 =
const std::string my_string_file2 =
const std::string my_string_file3 =
std::cout << "There was an error opening the file.\n";
//Read stuff here
while( my_stream >> x >> y )
//if we are here, then the read succeeded
std::cout << "I just read: " << x << " and " << y << std::endl;
std::cout << "An error occured while reading the file.\n";
std::cout << "Done reading file." << std::endl;
Last edited by monarch_dodra; May 6th, 2011 at 05:34 AM.
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Tags for this Thread
Click Here to Expand Forum to Full Width
This a Codeguru.com survey!