C++ 将 uint64_t 转换为 std::string
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7348051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert uint64_t to std::string
提问by Yakov
How can I transfer uint64_t value to std::string? I need to construct the std::string containing this value For example something like this:
如何将 uint64_t 值传输到 std::string?我需要构造包含此值的 std::string 例如这样的:
void genString(uint64_t val)
{
std::string str;
//.....some code for str
str+=(unsigned int)val;//????
}
Thank you
谢谢
采纳答案by Flexo
use either boost::lexical_castor std::ostringstream
使用boost::lexical_cast或std::ostringstream
e.g.:
例如:
str += boost::lexical_cast<std::string>(val);
or
或者
std::ostringstream o;
o << val;
str += o.str();
回答by dau_sama
In C++ 11 you may just use:
在 C++ 11 中,您可以只使用:
std::to_string()
it's defined in header
它在标题中定义
回答by jcoder
I use something like this code below. Because it's a template it will work with any type the supports operator<< to a stream.
我使用类似下面的代码。因为它是一个模板,所以它适用于任何支持 operator<< 到流的类型。
#include <sstream>
template <typename T>
std::string tostring(const T& t)
{
std::ostringstream ss;
ss << t;
return ss.str();
}
for example
例如
uint64_t data = 123;
std::string mystring = tostring(data);
回答by NMI
string genString(uint64_t val)
{
char temp[21];
sprintf(temp, "%z", val);
return temp;
}

