相当于 %05d,带有负数的 std::stringstream

Equivalent of %05d with std::stringstream for negative numbers?

本文关键字:std stringstream %05d 相当于      更新时间:2023-10-16

我正在尝试为 sprintfs 的 %05d 行为创建一个替代品。Althought,我在stackoverflow上发现了一个类似的问题,当我使用负数进行测试时,那里提出的解决方案对我不起作用。

做一个"sprintf(buf, "%05d", -12(",我得到"-0012",看起来不错。

使用字符串流、宽度和填充,我得到"00-12",在查看来自 std::basic_ios::fill 的文档时,接缝是合理的

填充字符

是输出插入函数在将结果填充到字段宽度时用于填充空格的字符。

但看起来不像是人们所希望的。

所以我很困惑,不知道我是否做错了什么明显的错误,或者来自 std 流的宽度/填充是否不容易支持这种情况。

可在代码板上找到可编译的测试代码。以下是基于流的转换的摘录:

std::string NumberToString(const long iVal, const int iNumDigit)
{
    std::stringstream ss;
    if      (iNumDigit >= 0) ss.fill(' ');
    else if (iNumDigit < 0)  ss.fill('0');
    ss.width(std::abs(iNumDigit));
    ss << iVal;
    return ss.str();
}

编辑1:解决方案:

为了将 std 流方法与 %05d 的 printf 格式相匹配,jrok 的解决方案可用于具有前导零的情况。这是新功能:

std::string NumberToString(const long iVal, const int iNumDigit)
{
    std::stringstream ss;
    if      (iNumDigit >= 0) ss.fill(' ');
    else if (iNumDigit < 0)  { ss.fill('0'); ss.setf(std::ios::internal, std::ios::adjustfield); }
    ss.width(std::abs(iNumDigit));
    ss << iVal;
    return ss.str();
}

使用流操纵器std::internal。它(连同std::leftstd::right(允许您指定填充字符的位置。例如

std::cout << std::setw(5) << std::setfill('0') << std::internal << -1;

将打印-0001 .