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

时间:2017-10-13 12:21:53

标签: 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

4 个答案:

答案 0 :(得分:36)

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

您需要在符号和值之间填充internal

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

答案 1 :(得分:11)

您可以在std::internal之前使用std::showpos juste(如图here所示)。

  

我们需要添加std :: internal标志来告诉流插入&#34;内部填充&#34; - 即,应在标志和号码的其余部分之间插入填充。

#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;
}

答案 2 :(得分:8)

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

std::cout << std::internal << std::setfill(0) << std::setw(3) << 1 << '\n';

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

答案 3 :(得分:0)

不幸的是,它应该如何运作。 &#39; 0&#39; 0用作 fill 字符,而不是数字的一部分。

要解决此问题,您必须单独输出+或 - :

std::ostringstream oss;
oss << "+-"[x<0];
oss << std::setw(2) << std::setfill('0') << std::abs(x);
return/cout/whatever oss.str();