什么是setw()的处理? [英] What's the deal with setw()?
问题描述
我最近被 ios_base :: width
和/或 setw
操纵器重置所有写入信息流的项目。
I recently was bitten by the fact that ios_base::width
and/or the setw
manipulator have to be reset with every item written to the stream.
也就是说,您必须这样做:
That is, you must do this:
while(whatever)
{
mystream << std::setw(2) << myval;
}
而不是这样:
mystream.width(2);
while(whatever)
{
mystream << myval;
}
好的。
但是有没有人知道为什么做这个设计决定呢?
有没有一些理由我缺少,或者这只是标准的一个黑暗的角落?
But does anyone know why this design decision was made? Is there some rationale that I'm missing, or is this just a dark corner of the standard?
其他流格式化修饰符SO问题)是粘性的,而 setw
不是。
Other stream formatting modifiers (as mentioned in the linked SO question) are 'sticky', while setw
is not.
推荐答案
我看到的方式是:你可以总是做下面的事情,如果你想要统一应用。
The way i see it is : You can always do something like below if you want it to be applied uniformly.
int width =2;
while(whatever)
{
mystream << std::setw(width) << myval;
}
但如果它是粘滞的,你提到:
but if it was sticky as you mention:
mystream.width(2);
while(whatever)
{
mystream << myval;
}
如果我想要一个不同的宽度每行我必须保持设置宽度。
and if i wanted a different width every line I have to keep setting width.
因此,这两种方法几乎都是一样的,我会喜欢或不喜欢他们,取决于我现在在做什么。
So essentially both approaches are almost the same, and i would like or dislike them depending on what i am doing now.
这篇关于什么是setw()的处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!