Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Generic String Conversion Question

0 views
Skip to first unread message

Jack

unread,
Nov 18, 2009, 6:37:57 AM11/18/09
to
Hi vc gurus,

template<typename ValueType>
std::string ConvertToString(ValueType value)
{
std::stringstream ss;
ss << value;
return ss.str();
}

With the above code snippet, I am able to
use
str = ConvertToString<DWORD>(temp1);
to obtain a decent string for DWORD numbers.

But it did not succeed with floats
with a number of predefined significant digits.

This is what I wanted to obtain, say,
0.0000001
But the function returns
-3e-006

In normal circumstances, we do
sprintf (buff, "%.6f", number);

How can I turn the above function
into a generic function which can accept
floating point numbers in anyway I want?
Thanks
Jack


Darko Miletic

unread,
Nov 18, 2009, 7:16:14 AM11/18/09
to Jack
You should use manipulators to specify output, and partial
specialization to implement differencies for specific type.

Furthermore a decimal constant is by default double not float. To make
it float you mas append f to it's end.

This is how I would do it:

#include <string>
#include <sstream>
#include <iomanip>

template<typename charT, typename ValueType>
std::basic_string<charT> ConvertToString(ValueType value)
{
std::basic_stringstream<charT> ss;
ss << value;
return ss.str();
}

template<typename charT>
std::basic_string<charT> ConvertToString(float value)
{
std::basic_stringstream<charT> ss;
ss << std::fixed << std::setprecision(8) << value;
return ss.str();
}

template<typename charT>
std::basic_string<charT> ConvertToString(double value)
{
std::basic_stringstream<charT> ss;
ss << std::fixed << std::setprecision(10) << value;
return ss.str();
}


And the usage

std::cout << ConvertToString<char>(0.0000001f) << std::endl;


Jack

unread,
Nov 18, 2009, 7:38:00 AM11/18/09
to
Hi Darko,
I'll give it a try!
Thanks a lot
Jack


mzdude

unread,
Nov 18, 2009, 8:30:12 AM11/18/09
to

if you are open to using boost look into lexical_cast

std::string b = boost::lexical_cast<std::string>( 10.456 );
double d = boost::lexical_cast<double>(b);

It does not allow for formatting, so you will get maximum precision
when casting floating point to string.

Jack

unread,
Nov 19, 2009, 12:29:17 AM11/19/09
to
Thanks mzdude,
I'll give it a try too
Jack


Jack

unread,
Nov 19, 2009, 12:48:34 AM11/19/09
to
nearly get there
But the <char> makes strings empty...
Thanks
Jack


Darko Miletic

unread,
Nov 19, 2009, 10:36:48 AM11/19/09
to Jack

I tried that on my VS 2005 and everything works fine. Can you show your
code?

0 new messages