Stringstream and its basic usage...

What is wrong with this code?
Suppose
1. tempString contains the following:"/454/665/4/"
2. i is always the position of the first integer after "/"
3. tempBuf points to the stringbuf of tempStream
4. tempVar is int

1
2
3
4
5
tempBuf->str(tempString.substr(i,tempString.find('/',i)-i));
cout<<tempBuf->str();
tempStream.flush();
tempStream>>tempVar;
cout<<tempVar;

I put this in a loop(if necessary, I'll put the rest of the code here also), and every time it should have different result(the next string of numbers should be assigned to tempVar), but it doesn't. I expect this:

454 454 665 665 4 4
(without the space, I put it for clearness)

but I get this instead:
454 454 665 454 4 454

So what is wrong with the code? Or maybe I am expecting something wrong...

Thanks in advance, and also, I have posted this in another thread, but didn't get an answer(although got answers for lots of other things, thanks shacktar, but I am in haste). Peace \/
You might have to clear the tempStream after calling tempStream>>tempVar;.

i.e.
1
2
tempStream.str("");
tempStream.clear(); //clear error flags 

I've found that you don't need to do that if you append a space after each number you input to the stringstream.

The following doesn't work (it prints "42 42" when I expect "42 54"):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
     int num;

     stringstream ss;

     ss<<"42";
     ss>>num;
     cout<<num;

     ss<<"54";
     ss>>num;
     cout<<" "<<num<<endl;

     return 0;
}


although the following works (note the spaces after the inputted numbers):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
     int num;

     stringstream ss;

     ss<<"42 ";
     ss>>num;
     cout<<num;

     ss<<"54 ";
     ss>>num;
     cout<<" "<<num<<endl;

     return 0;
}


this is because stringstreams expect a space as a delimiter. If you just give it a number (without a space afterwards), some error flags will be set and you won't be able to continue until you call .clear();

thanks shacktar

You're welcome :)
Last edited on
Awesome, really needed this(deadline coming soon :]). And although I am getting quite boring, THANKS again \o/! (no harm in gratefulness, right?)
btw,
this is because stringstreams expect a space as a delimiter

is this something you learnt from books or from experience? cause it wasn't mentioned in the Reference page. Or maybe I missed it...
I found that it was implied by examples such as this one:
http://www.cplusplus.com/reference/iostream/stringstream/stringstream/

Although, it should be something that is more clearly stated. Unfortunately, I don't think there's a way to change the delimiter character. You're welcome again :)
Last edited on
Topic archived. No new replies allowed.