# How to turn a float or double into a cstr or std::string?

## Recommended Posts

I know this question gets asked a lot, and I think it should be on c++'s top 50 FAQ, but because the forum search is MIA, and I suxors at the google searching for this particular topic, I'm coming to the For Beginners for some needed help. Does anyone body know any swav algorithms for turning floats or doubles into cstrings or std:strings, and how do they compare to the the standard c++ way of loading the data into a strstream and than doing the fancy stuff to get the type of data representation you want?

##### Share on other sites
jfclavette    1058
Well, the strstream technique is by far the best one. What's the problem ?

##### Share on other sites
hh10k    589
Remember strstream is deprecated. You need to use stringstream, which is declared in <sstream>.

##### Share on other sites
jfclavette    1058
Quote:
 Original post by hh10kRemember strstream is deprecated. You need to use stringstream, which is declared in .

Good catch. I still refer to them as strstream most of the time. [headshake]

##### Share on other sites
Wavarian    850
Since this is the beginner's forum, I'll give an example for what was mentioned above:

#include <iostream>#include <sstream>using namespace std;int main(int argCount, char* args[]){	stringstream s;	float value = 8.75f;	s << value;	cout << s.str() << "\n";	return 0;}

##### Share on other sites
SiCrane    11839
Or just use boost::lexical_cast.

##### Share on other sites
Ok cool everybody, I'll stick with stringstream, I was a tad interested in an algorithm to do it, but why reinvent the wheel eh?

I'll check out lexical_cast, and see how it compares with stringstream in terms of speed.

Thanks for the help!

##### Share on other sites
SiCrane    11839
boost::lexical_cast uses the stringstream method internally; with inlining it should be pretty much the same speed as stringstream. However, it does take into account some details that can screw you up using the stringstream method.