checking for EOF, reading input

Sep 8, 2011 at 4:28am
Hey everyone i am having a problem with reading input from a text file that looks like this:

9 1 1
1.2 -2.3 0.4
-2 -3 -4
+0 -2 8.85
2.345

The problem is that i am not reading the last line (2.345).

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

int main()
{
double a, b, c;
ifstream input("quadratic.dat");

input>>a>>b>>c;
while (!input.eof())
{
cout<<"a: "<<a<<" b:"<<b<<" c:"<<c<<endl;
input>>a>>b>>c;
}
return 0;
}

Thanks in advance





Last edited on Sep 8, 2011 at 4:30am
Sep 8, 2011 at 5:05am
You are trying to read 3 numbers, but the input just have 1, so you reach the end of file.
¿Could you explain the structure of the file?
Sep 8, 2011 at 5:08am
Because the last line contains only one number, the line extracting 3 values is failing (probably after a successful extraction for variable a?). This failure may be causing grief. Now, I am no expert with streams in C++, so I'll just tell you what I would do:

1. Never use multiple extraction statements because you never know when one will fail.
2. Read the entire line as a string, and then use a string stream to extract the 3 values. What will happen if you had:

0
12
231 3423 231

??? I imagine that multiple extraction statements would take data from different rows, and the variables would end up like this:

a = 0
b = 12
c = 231

This means that the next a will be 3423, and that the next C will take data from the next line, which could be highly undesirable.

3. Always loop while (stream.good()) and not just by eof(). The fail bit is as important.
Sep 8, 2011 at 5:27am
I wanted to extract 3 numbers at a time, i.e. 9, 1, 1 first, so i could send those 3 values to function first.

Then Repeat for the second set of numbers, 1.2 -2.3 0.4, send them to the same function

All this in a loop.

So

read form txt file,
cast the 3 values int variables (9,1,1)
send variables to function
return to main
read from txt file again
cast the 3 values int variables (1.2 -2.3 0.4)
send variables to function






Sep 8, 2011 at 3:09pm
¿then why the last line just got 1 number? ¿do you want "default" values for the others?

1. Never use multiple extraction statements because you never know when one will fail.
If it fails, you will know that it failed. However you can't know where it failed, ¿but do you care? If the data is corrupted, ¿what is the best that you can do?
2. I like to input things with spaces, some people use the enter key. You could read both that way.
3. while(input>>a>>b>>c) (if you accept the previous points)
Topic archived. No new replies allowed.