setw()不会影响读取整数字段 [英] setw() does not affect reading integer fields
问题描述
我写了这样的代码:
int d{ 0 };
cin >> setw(2) >> d;
但是看来 setw()
对读取整数没有影响.如果是这样,我们如何使用 istream
来实现 scanf()
的%2d
行为?
But it seems setw()
has no effect on reading integers. If so, how we could implement behaviour of %2d
of scanf()
with istream
?
推荐答案
setw()
不是设计的,不能用于整数类型.
setw()
is not designed to be used with integral types.
它会做什么?提取整数的最后两位十进制数字?如果您将 std :: hex
放入流中,将会发生什么?
What would it do? Extract the last two decimal digits of the integer? What would happen if you had put std::hex
into the stream?
最好的方法是先读取数字,然后自己处理.例如,如果要提取最低有效两位数,请随后使用 d%100
;否则,请使用.对负数进行额外的修正.
The best approach is to read the number then deal with it yourself. For example, if you want to extract the least significant two digits, use d % 100
subsequently; making an extra correction for negative numbers.
这篇关于setw()不会影响读取整数字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!