Jump to content
  • Advertisement
Sign in to follow this  
Hypherion

question about STL "string" class

This topic is 4391 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
Hi bud,

use std::stringstream;

Look that up on google and MSDN.

Dave

Share this post


Link to post
Share on other sites

#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
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
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
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
"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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!