DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   working with stringstream (http://www.daniweb.com/forums/thread152105.html)

Headerandy Oct 19th, 2008 5:49 am
working with stringstream
 
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;
}

Sci@phy Oct 19th, 2008 6:39 am
Re: working with stringstream
 
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}

Headerandy Oct 21st, 2008 4:44 am
Re: working with stringstream
 
[/ICODE][/QUOTE] thanks a million u sci@phy I've tried & it is working well as per my requirement


All times are GMT -4. The time now is 9:48 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC