PDA

View Full Version : c++ stringstream issue


oldmanstan
January 15th, 2006, 03:40 AM
ok, this is an edit, the below problem is solved, figured it out right after posting, i needed to include <string> and <sstream>, oops. however, what is the difference between ostringstream and stringstream?

Ok, here's what i'm trying to do, convert an int to a std::string. i'm trying to use the stringstream type, i'm basically copying an example i found using google, but mine won't compile, here's the code basically...


std::stringstream ResultStream;
ResultStream << i;
return ResultStream.str();


however, when i compile it using g++ i get the following error:

bigints.cpp:212: error: aggregate ‘std::stringstream ResultStream’ has incomplete type and cannot be defined

any ideas? thanks a bunch!

Viro
January 15th, 2006, 12:43 PM
std::stringstream is the superclass that contains some abstract methods. That's why you can't instantiate it directly. Instead, you should work with istringstream and ostringstream. You use istringstream when you want to convert a string to some primitive type like a float or an int. If you want to convert a float/int or something else to a string, use ostringstream.

If you're familiar to C, you should view istringstream as a kind of scanf and ostringstream as a kind of printf.

thumper
January 15th, 2006, 04:32 PM
std::stringstream is the superclass that contains some abstract methods. That's why you can't instantiate it directly. Instead, you should work with istringstream and ostringstream. You use istringstream when you want to convert a string to some primitive type like a float or an int. If you want to convert a float/int or something else to a string, use ostringstream.
Unfortunately not correct.

You can instantiate std::stringstream quite fine thank you very much ;)

In fact that is exactly what boost::lexical_cast (http://www.boost.org/libs/conversion/lexical_cast.htm) uses.

std::stringstream inherits from both std:: ostringstream and std::istringstream.

oldmanstan sorry, can't say why you are getting that error without seeing the code and your compilation command.


#include <boost/lexcal_cast.hpp>
//...
int val = 42;
std::string vals = boost::lexical_cast<std::string>(val);

emsee
December 26th, 2007, 05:31 PM
here is why:
you forgot this #include <sstream>
just fuxed same thing in my code