C++ Convert float to string?
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!
If I recall correctly, there is a function called itof. However, I think you'd be better off using std::stringstream, or boost::lexical_cast
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?
a simple method...
template <class T>std::string to_string(T & t){ std::stringstream s; s << t; return s.str();}
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.
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.
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?
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?
There's no difference between template <typename T> and template <class T> except for spelling.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement