Jump to content
  • Advertisement
Sign in to follow this  
InsaneBoarder234

C++ Convert float to string?

This topic is 4820 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

I'm writing a simple D3DXFONT wrapper class for my game, the class stores a C++ string to be rendered and has a set of Append() functions to append strings, ints and longs to the buffer. For ints and longs I create a char buffer and use itoa/ltoa to convert them to text and append them to the buffer but how can I do the same with a float? Thanks!

Share this post


Link to post
Share on other sites
Advertisement
char MyInfo[16];
float MyNumber;
MyNumber = 120.586;
wsprintf(MyInfo, "%f", MyNumber);


Using the above, the char string 'MyInfo' will read "120.586". My example is for Windows, so you may need to substitute 'sprintf' in the place of 'wsprintf'. Is that what you're trying to do?

Share this post


Link to post
Share on other sites
a simple method...

template <class T>
std::string to_string(T & t)
{
std::stringstream s;
s << t;
return s.str();
}

Share this post


Link to post
Share on other sites
If you're using C++, your best bet is to use std::stringstream, especially if you are using std::string or CString for your storage.

Dookie:
char MyInfo[16];
float MyNumber;
MyNumber = 120.586;
wsprintf(MyInfo, "%f", MyNumber);

Bad Dookie! You should be using snprintf here [snprintf(MyInfo, 16, "%f", MyNumber)] (_snwprintf for Win32). This is how buffer overflows are created. Although admittedly, 16 chars is probably big enough, who knows how printf may decide to format that number.

Share this post


Link to post
Share on other sites
Wow, thanks for the fast replies everyone.

I have done what three of you said and wrote a template function around std::stringstream.

The only thing is I used "template <typename T>". I'm not too hot with templates and it seems to work ok but would there be any difference if I used "template <class T>" instead?

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!