使用std :: stringstream将boost :: int64_t转换为字符串

Using std::stringstream to convert boost::int64_t large number to string.

本文关键字:转换 字符串 boost std stringstream 使用 int64      更新时间:2023-10-16

请参阅以下代码,调试和Show Convert在iPhone模拟器和设备(4s)上都成功,但我想知道它是如何工作的吗?请参阅http://www.cplusplus.com/reference/iostream/ostream/operator<</,boost :: int64_t没有Overload函数。

如果我使用此功能将任何任意boost :: int64_t类型转换?提前致谢。

std::stringstream mySS;
boost::int64_t large = 4294967296889977;
mySS<<large;
std::string str = mySS.str(); 

其起作用的原因是boost:int64_t确实是内置类型的类型(通常是cstdint中定义的std::int64_t或类似的类型),因此它可能最终与long long相同(或类似,取决于平台)。当然,stringstream::operator<<超载。

有关确切的定义,最好见boost/cstdint.hpp(1.51版)。

假设这通常可以在所有主要平台上使用,这可能是一个相对安全的选择。但是我怀疑任何人都可以为此提供保证。

如果您使用std::stringstream的目的是在整数和字符串之间转换,那么您可以做的最安全的事情就是使用Boost自己的转换方式:boost::lexical_cast(1.51版本)。这是完成的方式:

#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/lexical_cast.hpp>
int main()
{
  boost::int64_t i = 12;
  std::string    s = boost::lexical_cast<std::string>(i);
  std::cout << s << std::endl;
  return 0;
}