0

I am storing some data in a sting & I'm retriving it using stringstream but the problem is that it repeates last element two times.I could not understand why is this happning?Is there anyone who can help me on solving this problem?
Programme code is as follows:::::::::::::

#include<iostream>
#include<sstream>

using namespace std;

int main()
{
        int i,x;

        stringstream sstr;
        string line;

        for(i=0;i<3;i++) {
                getline(cin,line);

                sstr<<line;

                while(sstr) {
                        sstr>>x;
                        cout<<x<<" ";               //output repeates last element two times
                }
               
                cout<<endl;

                sstr.clear();
        }

        return 0;
}
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Headerandy
1

Reason is that sstr is set to false AFTER trying to read after EOF. So first you read last item, it's ok, when while sees no error, continues, but you can't read more, so x is assigned to last good reading (last number) AND then sstr is set to FALSE!

You need this: while (sstr>>x){//do stuff with x}

Votes + Comments
And I thought it was because the input and output flags weren't on - good deduction!
0

thanks a million u sci@phy I've tried & it is working well as per my requirement

Edited by mike_2000_17: Fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.