C++ 将 _int64 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4099448/
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 _int64 to a string
提问by Dave Powell
I had a question when providing an API
我在提供 API 时遇到了一个问题
if I ask for them to give me a _int64
10 digit hexadecimal number but my function internally takes strings how do I effectively convert that...
如果我要求他们给我一个_int64
10 位的十六进制数,但我的函数在内部接受字符串,我该如何有效地转换它...
as of right now I was just using string internally but for compatibility reasons i was using char*
c style so that give any system 32 or 64 it wouldn't matter. Is that the accurate thing to do? or am i wrong?
截至目前,我只是在内部使用字符串,但出于兼容性原因,我使用的是char*
c 样式,因此给任何系统 32 或 64 都无关紧要。这是正确的做法吗?还是我错了?
is there a problem using char*
vs _int64
?
使用char*
vs有问题_int64
吗?
回答by davidvandebunte
C++11 standardized the std::to_string
function:
C++11 标准化了std::to_string
函数:
#include <string>
int main()
{
int64_t value = 128;
std::string asString = std::to_string(value);
return 0;
}
回答by Steve Townsend
#include <string>
#include <sstream>
int main()
{
std::stringstream stream;
__int64 value(1000000000);
stream << value;
std::string strValue(stream.str());
return 0;
}
回答by Remy Lebeau
The best option is to change the function to not use strings anymore so you can pass the original __int64 as-is. __int64 works the same in 32-bit and 64-bit systems.
最好的选择是将函数更改为不再使用字符串,以便您可以按原样传递原始 __int64。__int64 在 32 位和 64 位系统中的工作方式相同。
If you have to convert to a string, there are several options. Steve showed you how to use a stringstream, which is the C++ way to do it. You can also use the C sprintf() or _i64toa() functions:
如果必须转换为字符串,有多种选择。Steve 向您展示了如何使用字符串流,这是 C++ 的方法。您还可以使用 C sprintf() 或 _i64toa() 函数:
__int64 value = ...;
char buffer[20];
sprintf(buffer, "%Ld", value);
__int64 value = ...;
char buffer[20];
_i64toa(value, buffer, 10);