Weird behavior when using stringstream

When I am using string stream twice it does not
accept the value second time
weird thing is same does work if the string passed before contains a space

1
2
3
4
5
6
7
8
9
10
11
stringstream ss;
string s1,s2;

s1 = "aaaaa";
ss.str(s1);
ss >> s2;
cout << s2<<' ';
s1 = "bbbbb";
ss.str(s1);
ss >> s2;
cout << s2;


Here the output is

 
aaaaa aaaaa


I expected

 
aaaaa bbbbb


The weird thing is it works just fine in this case

1
2
3
4
5
6
7
8
9
10
11
stringstream ss;
string s1,s2;

s1 = "aaaaa ccc";
ss.str(s1);
ss >> s2;
cout << s2<<' ';
s1 = "bbbbb";
ss.str(s1);
ss >> s2;
cout << s2;


Here the output is as expected;

 
aaaaa bbbbb


Can Someone please help me with why is this happeneng and how can i bypss this problem.

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
using namespace std;

int main() {
	string s1 {"aaaaa"}, s2;
	stringstream ss(s1);

	ss >> s2;
	cout << s2 << ' ';

	ss.clear();

	s1 = "bbbbb";
	ss.str(s1);

	ss >> s2;
	cout << s2 << '\n';
}


Note L12. a stringstream is a stream so it has the same states of eof, bad, fail etc. If the stream is not good, then the state has to be reset the same as you would with a file stream.


aaaaa bbbbb


The second example works because the extraction doesn't set eof the way the first example does.
Last edited on
Thanks for the fast reply that was really helpful! Much appreciated!!!
Topic archived. No new replies allowed.