将浮点ostream打印限制为一定长度?
这是相关主题 。
我正在寻找稍微不同的东西,我正在打印一个 4x4 浮点矩阵。事实上,我正在使用这个漂亮的打印方法来做到这一点,这将阻止我使用我更熟悉的 printf
格式。
我可以设置 ios_base::width() 来设置最小宽度来填充零和一,但是像 0.6666667 之类的东西会搞砸对齐。我想我可以设置精度,但它只影响有效数字的数量,而不影响该值生成的字符总数。我似乎无法在 ostream
上使用 unsetf
来设置“默认符号”...即使我可以这样做,我怀疑减号无论如何都会弄乱对齐。
有解决方法吗?
Here's a related topic.
I'm looking for something slightly different, I'm printing out a 4x4 floating point matrix. In fact I'm using this prettyprint method to do it, which will preclude me from using printf
formatting which I'm a little more familiar with.
I can set ios_base::width()
to set a minimum width to pad out the zeros and ones but the likes of 0.6666667
screws up the alignment. I figure I can set precision
but it only affects the number of significant figures and not the total number of char's produced by the value. I can't seem to use unsetf
on an ostream
to set 'default notation'... Even if I could do that I suspect a minus sign would mess up alignment anyway.
Is there a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的临时解决方案是
width(7)
和precision(4)
。它给了我小数点后 4 位数字和 3 个空格,用于放置减号、单个数字和小数点。我必须检查和修改宽度,以便容纳大于99.9999
或小于-9.9999
的(某些)值以保持对齐。这样做的好处是567890123
不会被打印为5678901
,它所做的只是取消对齐(很多情况下,它将被打印为567890123.0000
代码>)。My temporary solution is
width(7)
andprecision(4)
. It gives me 4 digits after the decimal point and 3 which is space to put the minus sign, a single digit, and the decimal point. I have to check and modify width in order to accomodate (some of the) values larger than99.9999
or less than-9.9999
to preserve alignment. This has the benefit that567890123
will not be printed as5678901
, all it will do is throw off alignment (a lot, it will be printed as567890123.0000
).