error checking for istringstream

hi everyone,
I'm trying to write a program for school which reads in from a text file, evaluates from scores in the file and then outputs to a new file.

so far I've got a getline going from the input into a string and then a istringsteam going into three ints. all of this is in a while loop.

all this works fine untill the input takes an empty line, after which the ints remain what they were before it for the rest of the execution of the program, even though the string apears keep moving through the input file. here's the relevant code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string line;
int x, y, z;
istringstream n;

if (in.fail())
cout << "Error: no input file" << endl;

while (getline(in, line))      
{
n.str(line);
n >> x >> y >> z;

out << "test" << line << x <<endl;
cout << line << x << y << y << endl;
cout << test(x, y, z);
}


where 'in' is an ifstream and 'out' is an ofstream and 'test' is a function.
I don't understand how the string 'line' can keep changing with each iteration and not change the istringstream 'n' going into the ints 'x, y, & z' (they get stuck with the values they had before the erronious empty line input). i also can't figure out how include a error checking mechanism to check that what comes out of 'n' is in fact an int. i've been trying to fail. somehow with 'n' but can't figure out how to.

any help or direction will be most welcome, thanks for any replies.
n>> x >> y >> z; If this fail, the istringstream stay in a state of error. So the next attempt will fail too.
n.clear(); This will reset the state (you could construct the stream inside the loop too)

However, why don't just read the numbers directly from the file?
while( in >> x>>y>>z)

[How] to check that what comes out of 'n' is in fact an int
you could use istream::peek() or try to read and check if you fail
Last edited on
wow,
thanks for your quick and comprehensive response. i will try these things. thus far i've included:
if (!n.fail())
just after the n << x << y << z line, which helps to put out an error message. but obviously does nothing for the error state.
thanks again.
Topic archived. No new replies allowed.