• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 180
  • Last Modified:

generic string conv

i have very little exposure in c++,pl dont neglect my question.
i need  a generic function which accepts any primitive datatype and converts it into a string(STL) .
eg: string convString(<type eg:double,long,> value)

i have used _fcvt() for double to string(char *,which i converted later), but i found "." is missing in the string.

and i also need a function which will  find the length of primitive datatypes not sizeof(type);

eg: double d = 1234.25
int size = mySize(1234.25);
size should contain a value 7(includes ".", if it has);


  • 2
1 Solution
#define mySize(x) (sizeof #x -1)
template <class T>
string ConvString( T a)
   strstream s;
   s << a;
return s.str();

This function will convert any C++
data type to a string but ..
This will change the size.

e.g ConvString( 2.3)

It may become 2.30000
and size will be 7 instead of
3 ( as u might expect).

But if u specify the correct
parameter for strstream s for
floating variables then u can
use it.

I think it is very difficult to
maintain the size e.g.

ConvString( +2.3)
You might expect the size 4 but
it will be 3 as + may miss.

But my function will convert
it to a string.
#define ConvString(x) #x
>> i need  a generic function which accepts any
>> primitive datatype and converts it
>> into a string(STL)
Use the stringstream class for this.  You can output information to the class with << just like any other stream.  Then you can obtain all the formatted information written to the class as a string.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now