setw() 有什么关系?
我最近被以下事实所困扰: ios_base::width
和/或 setw
操纵器必须是 将每个项目写入流中进行重置。
也就是说,你必须这样做:
while(whatever)
{
mystream << std::setw(2) << myval;
}
而不是这样:
mystream.width(2);
while(whatever)
{
mystream << myval;
}
好吧,好吧。
但有人知道为什么做出这个设计决定吗? 我是否缺少一些基本原理,或者这只是标准的一个黑暗角落?
其他流格式化修饰符(如链接的 SO 问题中提到的)是“粘性的”,而 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;
}
Rather than this:
mystream.width(2);
while(whatever)
{
mystream << myval;
}
Ok, fine.
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?
Other stream formatting modifiers (as mentioned in the linked SO question) are 'sticky', while setw
is not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哪些操纵器应该只影响下一个操作的决定似乎基于逻辑和经验观察,这些观察倾向于更好地考虑常见功能需求,因此程序员更容易编写和正确执行。
以下几点让我觉得相关:
some_stream << x
应该在大多数情况下都能正常工作,setfill()
不相关,除非有待处理的setw()
,因此不会对some_stream << x
语句名列榜首hex
和oct
)是持久的,但它们的使用通常在代码块中,要么弹出先前的状态,要么(令人讨厌但更容易)将其设置回十进制由此得出的答案的要点你的问题...
setw()
是持久的,则需要在每个流语句之间重置它以防止不必要的填充...The decisions of which manipulators should affect only the next operation seem to be based on logical and empirical observations about what tends to factor common functional needs better, and hence be easier for the programmer to write and get right.
The following points strike me as relevant:
some_stream << x
should just work right most of the timesetfill()
is not relevant unless there's a pendingsetw()
, so won't adversely affect thesome_stream << x
statement topping our listhex
andoct
are persistent, but their use is typically in a block of code that either pops the prior state or (nasty but easier) sets it back to decimalThe point leading from this that answers your question...
setw()
were presistent, it would need to be reset between each streaming statement to prevent unwanted fill...我的看法是:如果您希望统一应用它,您可以随时执行如下操作。
但如果它像你提到的那样粘:
如果我想要每行不同的宽度,我必须继续设置宽度。
所以本质上这两种方法几乎是相同的,我喜欢或不喜欢它们取决于我现在在做什么。
The way i see it is : You can always do something like below if you want it to be applied uniformly.
but if it was sticky as you mention:
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.