views:

33

answers:

3

My input file is:

2 5 <-- extra space at the end
4 <--extra space at the end

int main(){
    ifstream input("input.txt");
    istream& in = input;
    string line1;

    while( getline(in,line1)){
        istringstream number1(line1);

        while(number1.good()){
            number1 >> temp1;
            cout<<temp1<<endl;
        }
}
input.close();
}

The problem is with the extra space at the end of the line my output is:
2
5
5
4
4
which is not what i want.. but if i remove the extra space it would work:
2
5
4

why is this happening? and how can i fix it so that even with extra spaces it reads the correct input? Any help would be appreciated. Thanks!

+3  A: 

Try changing this:

    while(number1.good()){
        number1 >> temp1;
        cout<<temp1<<endl;
    }

To:

    while (number1 >> temp1)
        cout << temp1 << endl;

and see if it doesn't work better. The problem isn't that it's reading the last blank as an element, but that stream.good() remains true until after a read that fails, so you're executing the loop once too often.

Alternatively, replace the whole thing with something like this:

int main() { 
    ifstream input("input.txt");

    std::copy(istream_iterator<int>(input),
              istream_iterator<int>(),
              ostream_iterator<int>(cout, "\n"));
    return 0;
}
Jerry Coffin
+4  A: 

The problem is with the while (number1.good()) loop. The number1 fail state will not be set until after the number1 >> temp1 extraction fails, but you don't test the fail state until the next time the loop condition is tested, which is after you print out the result of that extraction. You should change the inner loop to:

while (number1 >> temp1)
{
    std::cout << temp1 << std::endl;
}

This will extract the value, then test whether the extraction succeeded and will break out of the loop if the extraction fails, which is the behavior you want.

James McNellis
Thanks again for your help and explanation!
eNetik
A: 

Two things:

You're abusing streams here IMHO. There is no need for a second stream. You can simply:

int main()
{
    ifstream input("input.txt");
    string line1;
    int temp1; // <-- you forgot this in your question I believe

    while( in >> temp1 )
    {
        cout<<temp1<<endl;
    }
    input.close();
}

Secondly, I think the problem is your number1.good() call. this does not guarantee all bad stream bits. It's best to check extraction using the extraction statement itself like I did above.

rubenvb