working with stringstream

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2008
Posts: 6
Reputation: Headerandy is an unknown quantity at this point 
Solved Threads: 0
Headerandy Headerandy is offline Offline
Newbie Poster

working with stringstream

 
0
  #1
Oct 19th, 2008
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:::::::::::::
  1. #include<iostream>
  2. #include<sstream>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int i,x;
  9.  
  10. stringstream sstr;
  11. string line;
  12.  
  13. for(i=0;i<3;i++) {
  14. getline(cin,line);
  15.  
  16. sstr<<line;
  17.  
  18. while(sstr) {
  19. sstr>>x;
  20. cout<<x<<" "; //output repeates last element two times
  21. }
  22.  
  23. cout<<endl;
  24.  
  25. sstr.clear();
  26. }
  27.  
  28. return 0;
  29. }
Last edited by Ancient Dragon; Oct 19th, 2008 at 8:05 am. Reason: add code tags
Reply With Quote Quick reply to this message  
Join Date: Sep 2008
Posts: 273
Reputation: Sci@phy will become famous soon enough Sci@phy will become famous soon enough 
Solved Threads: 42
Sci@phy's Avatar
Sci@phy Sci@phy is offline Offline
Posting Whiz in Training

Re: working with stringstream

 
1
  #2
Oct 19th, 2008
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}
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 6
Reputation: Headerandy is an unknown quantity at this point 
Solved Threads: 0
Headerandy Headerandy is offline Offline
Newbie Poster

Re: working with stringstream

 
0
  #3
Oct 21st, 2008
[/ICODE][/QUOTE] thanks a million u sci@phy I've tried & it is working well as per my requirement
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC