Sign in to follow this  
Hypherion

question about STL "string" class

Recommended Posts

Hypherion    140
Hello, i was wondering how would i be able to get an integer transformed into a string. if for example i have int x=5; how would i do it so that i got a <string> b with that value? sorry for the rather stupid question :)

Share this post


Link to post
Share on other sites
rip-off    10979

#include <sstream>

template< class Out, class In >
Out cast( const In &in )
{
std::stringstream str;
str << in;
Out out;
str >> out;
return out;
}

int main()
{
int x = cast<int>("15");
std::string str = cast<std::string>(x);
// etc...
}




Quote:

sorry for the rather stupid question :)


Don't worry, its not something that would be obvious, it's not a stupid question.

Share this post


Link to post
Share on other sites
Hypherion    140
thanks for the fast reply and help.

Thought string had a cast already implemented (and i just missed it) but aparently not :).

Learning something new every day.

Share this post


Link to post
Share on other sites
Enigma    1410
You really ought to grab the Boost libraries and use Boost.Lexical_Cast, since that is a robust and well tested implementation of the same with well defined error behaviour (i.e. with rip-offs implementation if you cast the string "10 + 5" to an int you get 10, whereas boost::lexical_cast will report an error)

Σnigma

Share this post


Link to post
Share on other sites
Hypherion    140
ummm aparently i'm geting lots of errors with the inclusion of sstream


45 D:\Dev-Cpp\include\c++\3.4.2\istream:46, from D:\Dev-Cpp\include\c++\3.4.2\sstream In file included from D:/Dev-Cpp/include/c++/3.4.2/istream:46, from D:/Dev-Cpp/include/c++/3.4.2/sstream
292:22 D:\Dev-Cpp\include\c++\3.4.2\limits macro "max" requires 2 arguments, but only 1 given
320 D:\Dev-Cpp\include\c++\3.4.2\limits expected `;' before "throw"
323 D:\Dev-Cpp\include\c++\3.4.2\limits expected `;' before "static"



any ideas?

Share this post


Link to post
Share on other sites
Zahlman    1682
"max" should not be a macro; in that context it should probably refer to the function std::max. If you're including windows.h, you might need to #define NOMINMAX on the line before you include it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this