我正在使用std::ostringstream将双精度格式化为具有特定格式的字符串(使用撇号作为千位分隔符)。然而,在某些情况下,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;
}
关于 ideone 的代码
left
、right
和 internal
有三个选项。
您希望在符号和值之间internal
填充。
stream << std::setfill( '0' ) << std::internal; // Zero-padded
std::showpos
之前使用 std::internal
juste(如此处所示)。
我们需要添加 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;
}
字符与任何类型一起使用以填充给定宽度。默认情况下,填充字符位于值的左侧,这就是您在这些零中看到的内容。解决方案是覆盖该默认值并告诉流将填充字符放入文本中:
std::cout << std::internal << std::setfill(0) << std::setw(3) << 1 << 'n';
还可以使用 std::left
或 std::right
将填充字符放在值的左侧或值的右侧。
不幸的是,这就是它应该如何工作。"0"用作填充字符,而不是数字的一部分。
要修复它,您必须分别输出 + 或 - :
std::ostringstream oss;
oss << "+-"[x<0];
oss << std::setw(2) << std::setfill('0') << std::abs(x);
return/cout/whatever oss.str();