views:

154

answers:

6
+3  Q: 

Data Type Convert

Is there any function in C++ which converts all data types (double, int, short, etc) to string?

+7  A: 

Usually you'll use the << operator, in conjunction with (for example) a std::stringstream.

TreDubZedd
+2  A: 

There is no built-in universal function, but boost::lexical_cast<> will do this.

jeffamaphone
+4  A: 

http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm

aaa
+1, even though a code example is ALWAYS welcome
Matthieu M.
+3  A: 

If boost is not an option (it should always be, but just in case):

#include <sstream>
#include <string>

template<class T1, class T2>
T1 lexical_cast(const T2& value)
{
    std::stringstream stream;
    T1 retval;

    stream << value;
    stream >> retval;

    return retval;
}

template<class T>
std::string to_str(const T& value)
{
    return lexical_cast<std::string>(value);
}

Boost has a similar idea, but the implementation is much more efficient.

sukru
+1  A: 

Why do you need this conversion? A lot of languages have variant types which auto-convert, and this can lead to wanting that behavior in C++ even though there may be a more canonical way of implementing it.

For example if you're trying to do output, using a (string)stream of some sort is probably the way to go. If you really need to generate and manipulate a string, you can use boost::lexical_cast http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm.

Mark B
+1  A: 

Here is the one I use from my utility library. This was condensed from other posts here on stackoverflow, I am not claiming this as my own original code.

#include <string>
#include <sstream>

using namespace std;

template <class T>
string ToString(const T& Value) {
    stringstream ss;
    ss << Value;
    string s = ss.str();
    return s;
}

also, another handy string formatting utility I use:

#include <string>
#include <stdarg.h> /* we need va_list */

// Usage: string myString = FormatString("%s %d", "My Number =", num);
string FormatString(const char *fmt, ...) {

    string retStr;

    if (NULL != fmt) {
        va_list marker = NULL;
        va_start(marker, fmt);
        size_t len = 256 + 1; // hard size set to 256
        vector <char> buffer(len, '\0');
        if (vsnprintf(&buffer[0], buffer.size(), fmt, marker) > 0) {
            retStr = &buffer[0]; // Copy vector contents to the string
        }
        va_end(marker);
    }

    return retStr;
}
SuperJames