Question

I find myself having to std::cout various double variables. I've made a simple function to convert a double to a std::string, which I can then use with std::cout etc.

// Convert a double to a string.
std::string dtos(double x) {
    std::stringstream s;
    s << x;
    return s.str();
}

The function seems to work OK, but my question is: does this approach have any (bad) memory implications ie. am I allocating unecessary memory, or leaving anything 'dangling'?

Thanks guys Pete

Was it helpful?

Solution

No, your code is OK, read the comments on the code:

std::string dtos(double x) {
    std::stringstream s;  // Allocates memory on stack
    s << x;
    return s.str();       // returns a s.str() as a string by value
                          // Frees allocated memory of s
} 

In addition, you can pass a double to cout directly.

OTHER TIPS

Surprised no one mentioned this, but you could genarlize that algorithm for any type, using templates.

Like so:

template<typename T>
std::string to_string(const T& obj)
{
    std::ostringstream s;
    s << obj;
    return s.str();
}

That way you can easily convert to a string, like so:

int x = 5;
to_string(x); // will convert the integer to a string

to_string(32); // constants works
to_string<double>(302); // you can explicitly type the type you wish to convert

Example usage is on this link.

Also, as stated by other people, there's no memory going anywhere. Also, I would like to mention, that since you're only writing to a string stream, perhaps you should use std::ostringstream for (1) further clarification when people read your code and (2) no mistakes of using >> instead of <<

You don't have to change doubles to strings to use std::cout.

cout << x; 

will work just fine as

cout << dtos(x); 

And if you want to change double to string for other reasons then you can use you can use std::to_string in C++11.

Other than that your code is just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top