开发者

Data Type Convert

Is there any function in C++ which converts all data types (dou开发者_StackOverflow社区ble, int, short, etc) to string?


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


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


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.


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


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.


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;
}


For this use stringstream. First include the header file as #include . Then create an object of stringstream and using stream insertion operator (<<) pass the contents you want to convert as string. Ex:

#include <iostream>
#include <sstream>
int main(){
    std::string name = "Ram";
    float salary = 400.56;
    std::stringstream obj;
    obj << name << " salary: " << salary;
    std::string s = obj.str();
    std::cout << s;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜