Sign in to follow this  

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

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Quote:
Original post by hh10k
Remember strstream is deprecated. You need to use stringstream, which is declared in <sstream>.


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

Share this post


Link to post
Share on other sites
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 this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this