views:

100

answers:

1

I have a file which contains three integers per line. When I read the line I use a stringstream to separate the values, but it only reads the first value as it is. The other two are read as zero's.

ifstream inputstream(filename.c_str());
if( inputstream.is_open() ){

    string line;
    stringstream ss;

    while( getline(inputstream, line) ){
        //check line and extract elements
        int id;
        double income;
        int members;

        ss.clear();
        ss.str(line);
        ss >> id >> income >> members;*emphasized text*
    }
}

In the case above, id is extracted correctly, but income, and members get assigned zero instead of the actual value.

EDIT: Solved

Never mind. The code works correctly. The error was in my print statement. I had a for loop printing the array at the same index every time.

+1  A: 

Why don't you read directly from the file?

while( inputstream ) {
    if( ! inputstream >> id ) ...
    if( ! inputstream >> income ) ...
    if( ! inputstream >> members ) ...
}
wilhelmtell
This has the disadvantage of not correctly detecting an ill-formatted input. By reading a single line, you can guarantee that each line has the expected data on it.
James McNellis
I agree, but if the language requires that the user separates tuples by a newline it doesn't mean the parser must enforce it. Of course, if the language requires the _parser_ enforce newlines in the input then that's a different story. @user69514, your input on this?
wilhelmtell
If there's an ill-formatted line then the results are roughly undefined with my code. For example if there are three line and the first line has only one value then the parser will fail only at the list line. How should the code behave when there's an input error?
wilhelmtell