943,772 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 780
  • C++ RSS
Oct 19th, 2008
0

working with stringstream

Expand Post »
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:::::::::::::
C++ Syntax (Toggle Plain Text)
  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
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Headerandy is offline Offline
6 posts
since Oct 2008
Oct 19th, 2008
1

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}
Reputation Points: 110
Solved Threads: 43
Posting Whiz in Training
Sci@phy is offline Offline
279 posts
since Sep 2008
Oct 21st, 2008
0

Re: working with stringstream

[/ICODE][/QUOTE] thanks a million u sci@phy I've tried & it is working well as per my requirement
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Headerandy is offline Offline
6 posts
since Oct 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Need help removing number from an array
Next Thread in C++ Forum Timeline: writing functions.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC