相当于 %05d,带有负数的 std::stringstream
Equivalent of %05d with std::stringstream for negative numbers?
我正在尝试为 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::left
和std::right
(允许您指定填充字符的位置。例如
std::cout << std::setw(5) << std::setfill('0') << std::internal << -1;
将打印-0001
.
相关文章:
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- std::stringstream 返回字符 *
- std::stringstream::flush() 应该做什么吗?
- 静态 std::stringstream 的叮当整警告
- 为什么 {fmt} 比 std::stringstream 慢?
- C++命令末尾的 std::stringstream 空格
- 返回 std::stringstream - 编译失败
- 流从STD :: Stringstream带有空间的流
- 用std :: stringstream inline代替字符
- C STD :: Stringstream操作优化
- What value should `std::stringstream::fail()` return after r
- 使用Boost Karma替换STD :: stringstream double到STD :: String Conv
- 从 std::stringstream 读取uint8_t为数字类型
- 重置std :: stringstream格式标志
- 如何将“char *”深度复制到std::stringstream
- 将内存缓冲区写入 std::stringstream
- 如何初始化 std::stringstream
- STD :: Stringstream一次仅支持一个输入
- 用std :: stringstream读取/写作无符号字节
- 使用std :: stringstream将boost :: int64_t转换为字符串