std::stringstream as a class member

Started by
4 comments, last by TheFlyingDutchman 16 years, 2 months ago
Hello there. I am having a problem with std::stringstream as a class member. I am using it in my class for conversion from int to string etc. Its pretty straightforward, really: Header:

#include <string>
#include <sstream>

//(...)

std::stringstream ss;

Source:

//(...)

ss << mNumber;
ss.str() >> this->mText;

I am getting following compile errors:
Quote: d:\hge\projects\temp\temp\digitfield.cpp(39) : error C2784: 'std::basic_istream<_Elem,_Traits> &std::operator >>(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::basic_string<_Elem,_Traits,_Ax>' with [ _Elem=char, _Traits=std::char_traits<char>, _Ax=std::allocator<char> ] d:\programy\microsoft visual studio 8\vc\include\string(425) : see declaration of 'std::operator >>'
Advertisement
What type is 'mText'?
std::stringstream::str() returns a std::string, and there's no operator >> that takes two std::strings.

You probably want:
this->mText = ss.str();

EDIT: Err, no, I'm talking crap.
EDIT #2: No, I was right [smile]

[Edited by - Evil Steve on February 19, 2008 5:49:06 AM]
Your code doesn't work for the same reason that:
std::string x( "someString" );std::string y;y << x;// ORx >> y;


doesn't work. It actually has nothing to do with stringstreams, which I suspect is due to the fact that std::string provides no operator >>, which takes two std::string objects, but Evil Steve has already pointed that out and he thinks he's talking crap, so maybe I'm wrong after all[smile]

Try the following code instead:
std::stringstream ss;ss << mNumber;this->mText = ss.str();
Right, of course! Silly me for not noticing that.

Thanks!
Even a bit nicer (though, it depends on your needs) might be:

std::stringstream ss;ss << mNumber;// this extracts only the last string from ssss >> this->mText;

This topic is closed to new replies.

Advertisement