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;
}

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}

commented: And I thought it was because the input and output flags weren't on - good deduction! +4

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.