C++中是否有函数将所有数据类型(double
,int
, short
等)转换为string
?数据类型转换
Q
数据类型转换
3
A
回答
7
通常,您将使用<<
运算符,并结合(例如)std :: stringstream。
2
没有内置的通用功能,但boost::lexical_cast<>会这样做。
4
+0
+1,即使代码示例总是欢迎 – 2010-07-21 06:58:55
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_cast
http://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;
}
相关问题
- 1. 数据类型转换
- 2. 转换数据类型
- 3. Flex数据类型转换
- 4. Postgres数据类型转换
- 5. 转换数据类型
- 6. MSSQL数据类型转换
- 7. MATLAB:从char数据类型转换为符号数据类型
- 8. Haskell数据类型转换问题
- 9. 无法转换数据类型
- 10. DynamoDBMapper转换变量数据类型
- 11. 数据类型转换为SSIS?
- 12. 数据类型转换错误
- 13. 数据类型转换问题
- 14. 访问数据类型转换为Boolean
- 15. jQuery AJAX JSON数据类型转换
- 16. 转换SSIS中的数据类型
- 17. 转换表列数据类型VARBINARY
- 18. 转换数据类型的方法
- 19. Python Pandas转换列数据类型
- 20. Informatica的数据类型转换
- 21. WCF数据服务类型转换
- 22. 转换失败“****”为int数据类型
- 23. Python自动转换数据类型
- 24. 在mysql中转换数据类型
- 25. 将C数据类型转换为Python
- 26. 转换用户数据类型
- 27. 在熊猫中转换数据类型
- 28. 转换的SortedMap数据类型
- 29. 数据类型转换为Mysql或python
- 30. HBase Shell数据类型转换
虽然没有一个确切的重复,在这个问题的答案提供的常用方法转换内置类型为字符串:http://stackoverflow.com/questions/228005/alternative-to-itoa -for-converting-integer-to-string-c – 2010-07-20 18:13:05
[sprintf](http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/) – 2010-07-20 18:13:42
@Kirill'sprintf' is C. There are better,type C++中的安全选择。 – 2010-07-20 18:17:46