【问题标题】:boost::lexical_cast int to string padding with zerosboost::lexical_cast int 用零填充字符串
【发布时间】:2014-01-15 08:03:17
【问题描述】:

我需要使用生成的名称创建文件。我使用boost::lexical_cast 将整数转换为std::string。是否有可能获得带有填充零的字符串? 我没有c++11 tools,只有MSVS 2008 支持的所有内容。

例子:

int i = 10;
std::string str = boost::lexical_cast<std::string>(i);

// str = "10"
// expect str = "000010"

附言请不要建议使用 sprintf。

【问题讨论】:

  • 如果你想保持对它的感觉,只需编写一个模板化函数,它在内部使用 std::ostringstream 但添加填充(可能带有指定整体宽度的参数?)....

标签: c++ string boost lexical-cast


【解决方案1】:

为什么是boost::lexical_cast?使用std::stringstream

std::ostringstream ss;
ss << std::setw(6) << std::setfill('0') << i;
const std::string str = ss.str();

【讨论】:

  • setwsetfill&lt;iomanip&gt; 中声明。 setfill 被插入到output streams 上,所以最好使用std:ostringstream。形成更多信息setwsetfill
【解决方案2】:

您可以使用std::ostringstream 和普通流manipulators 进行格式化。

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2011-05-18
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多