C++ Convert float to string?

Started by
10 comments, last by Dookie 18 years, 7 months ago
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!
Progress is born from the opportunity to make mistakes.

My prize winning Connect 4 AI looks one move ahead, can you beat it? @nickstadb
Advertisement
I'd wrap a template function around std::stringstream
_______________________________ ________ _____ ___ __ _`By offloading cognitive load to the computer, programmers are able to design more elegant systems' - Unununium OS regarding Python
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?
"The crows seemed to be calling his name, thought Caw"
a simple method...
template <class T>std::string to_string(T & t){        std::stringstream s;        s << t;        return s.str();}

This space for rent.
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.
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?
Progress is born from the opportunity to make mistakes.

My prize winning Connect 4 AI looks one move ahead, can you beat it? @nickstadb
There's no difference between template <typename T> and template <class T> except for spelling.
Not AFAIK. Actually, 'typename' is preferred AFAIK.
Ok, thanks very much for the help!
Progress is born from the opportunity to make mistakes.

My prize winning Connect 4 AI looks one move ahead, can you beat it? @nickstadb

This topic is closed to new replies.

Advertisement