c++ - std::ostringstream 将登录放在错误的位置?

标签 c++

我正在使用 std::ostringstream 将 double 格式化为具有特定格式的字符串(使用撇号作为千位分隔符)。然而,在某些情况下,ostringstream 给了我一个与我预期不同的结果。

据我所知,下面代码的预期输出应该是“+01”;相反,它输出“0+1”。我在这里做错了什么,我怎样才能得到我需要的结果?

#include <iomanip>
#include <iostream>
#include <sstream>

int main() 
{
    std::ostringstream stream;
    stream << std::showpos; // Always show sign
    stream << std::setw(3); // Minimum 3 characters
    stream << std::setfill( '0' ); // Zero-padded
    stream << 1; // Expected output: "+01"

    std::cout << stream.str(); // Output: "0+1"
    return 0;
}

Code on ideone

最佳答案

填充有三个选项,left, right, and internal .

你想要 internal 填充,在符号和值之间。

stream << std::setfill( '0' ) << std::internal; // Zero-padded

关于c++ - std::ostringstream 将登录放在错误的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46729847/

相关文章:

c++ - 为什么 C++ 禁止 final 类的私有(private)继承?

c++ - reinterpret_cast vs c style cast

c++ - Directx C++ - 绘制 DNA 形状

C++:有没有什么好的读/写方法而不用在函数名中特别说明字符类型? (cout 与 wcout 等)

c++ - 生命游戏 - 算法问题 C++

模板类型的 C++ Constexpr 成员

c++ - 链接 netpbm 库时出现问题

c++ - 如何在 C++ 中创建 constexpr 函数

c++ - `POLLOUT` Linux函数中的 `poll`事件是什么意思?

c++ - 用两个 vector 排序