登录错误的位置std :: ostringstream?

dow*_*ash 27 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;
}
Run Code Online (Sandbox Code Playgroud)

关于ideone的代码

Bo *_*son 38

有三个选项用于填充,left,right,和internal.

你想要internal在标志和价值之间填充.

stream << std::setfill( '0' ) << std::internal; // Zero-padded
Run Code Online (Sandbox Code Playgroud)


inf*_*ero 12

您可以使用std::internal中庸之道之前std::showpos(如图所示这里).

我们需要添加std :: internal标志来告诉流插入"内部填充" - 即填充应插入符号和数字的其余部分之间.

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

int main() 
{
    std::ostringstream stream;

    stream << std::setfill('0');
    stream << std::setw(3);
    stream << std::internal;
    stream << std::showpos;
    stream << 1; 

    std::cout << stream.str(); // Output: "+01"
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*ker 9

填充字符用于任何类型以填充给定宽度.默认情况下,填充字符位于值的左侧,这就是您使用这些零看到的内容.解决方案是覆盖该默认值并告诉流将填充字符放在文本中:

std::cout << std::internal << std::setfill(0) << std::setw(3) << 1 << '\n';
Run Code Online (Sandbox Code Playgroud)

您还可以使用std::leftstd::right将填充字符放在值的左侧或值的右侧.