2010-07-20 112 views
3

C++中是否有函数将所有数据类型(double,int, short等)转换为string数据类型转换

+0

虽然没有一个确切的重复,在这个问题的答案提供的常用方法转换内置类型为字符串:http://stackoverflow.com/questions/228005/alternative-to-itoa -for-converting-integer-to-string-c – 2010-07-20 18:13:05

+0

[sprintf](http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/) – 2010-07-20 18:13:42

+2

@Kirill'sprintf' is C. There are better,type C++中的安全选择。 – 2010-07-20 18:17:46

回答

7

通常,您将使用<<运算符,并结合(例如)std :: stringstream。

3

如果提升不是一个选项(这应该始终,但以防万一):

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

加速也有类似的想法,但执行效率要高得多。

1

为什么你需要这种转换?很多语言都具有自动转换的变体类型,并且这可能导致想要C++中的行为,即使可能有更具规范的实现方式。

例如,如果你想要做输出,使用某种类型的(字符串)流可能是要走的路。如果您确实需要生成并处理字符串,则可以使用boost::lexical_casthttp://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm

1

这是我从我的实用程序库中使用的一个。这是从其他帖子浓缩在这里stackoverflow,我不是声称这是我自己的原始代码。

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

此外,另一个便利的字符串格式化工具使用:

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

对于这种使用stringstream的。 首先将头文件包含为#include。 然后创建一个stringstream对象并使用流插入操作符(< <)将要转换的内容作为字符串传递。 例如:

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