在 C++ 中将 uint64 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3113413/
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
Converting an uint64 to string in C++
提问by Bilthon
What's the easiest way to convert an uint64 value into a standart C++ string? I checked out the assign methods from the string and could find no one that accepts an uint64 (8 bytes) as argument.
将 uint64 值转换为标准 C++ 字符串的最简单方法是什么?我检查了字符串中的分配方法,但没有找到接受 uint64(8 字节)作为参数的方法。
How can I do this?
我怎样才能做到这一点?
Thanks
谢谢
回答by Frunsi
The standard way:
标准方式:
std::string uint64_to_string( uint64 value ) {
std::ostringstream os;
os << value;
return os.str();
}
If you need an optimized method, then you may use this one:
如果您需要优化的方法,那么您可以使用此方法:
void uint64_to_string( uint64 value, std::string& result ) {
result.clear();
result.reserve( 20 ); // max. 20 digits possible
uint64 q = value;
do {
result += "0123456789"[ q % 10 ];
q /= 10;
} while ( q );
std::reverse( result.begin(), result.end() );
}
回答by Randolpho
#include <sstream>
std::ostringstream oss;
uint64 i;
oss << i;
std:string intAsString(oss.str());
回答by Greg Domjan
more descriptive than streams I think is lexical_cast
比我认为的流更具描述性 lexical_cast
uint64 somevalue;
string result = boost::lexical_cast<string>(somevalue);
回答by Chris
I think you want to output it to a stringstream. Start here:
我认为您想将其输出到字符串流。从这里开始:
回答by Patrick
C++: Use a stringstream
C++:使用字符串流
C: sprintf (buffer,"%I64ld",myint64);
C: sprintf (buffer,"%I64ld",myint64);
回答by davidvandebunte
C++11 standardized the to_string
function mentioned by Frunsi as std::to_string
:
C++11 将to_string
Frunsi 提到的函数标准化为std::to_string
:
#include <string>
int main()
{
uint64_t value = 128;
std::string asString = std::to_string(value);
return 0;
}
回答by Edward Strange
std::string converted(reinterpret_cast<char*>(&my_int64),
reinterpret_cast<char*>((&my_int64)+1));