converting _int64 to a string
I had a question when provid开发者_开发技巧ing an 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...
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?
is there a problem using char*
vs _int64
?
C++11 standardized the std::to_string
function:
#include <string>
int main()
{
int64_t value = 128;
std::string asString = std::to_string(value);
return 0;
}
#include <string>
#include <sstream>
int main()
{
std::stringstream stream;
__int64 value(1000000000);
stream << value;
std::string strValue(stream.str());
return 0;
}
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.
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:
__int64 value = ...;
char buffer[20];
sprintf(buffer, "%Ld", value);
__int64 value = ...;
char buffer[20];
_i64toa(value, buffer, 10);
精彩评论