setw() does not affect reading integer fields

前端 未结 1 713
臣服心动
臣服心动 2021-01-19 01:08

I wrote a code like this:

int d{ 0 };
cin >> setw(2) >> d;

But it seems setw() has no effect on reading integers.

相关标签:
1条回答
  • 2021-01-19 01:57

    setw() is not designed to be used with integral types.

    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?

    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.

    0 讨论(0)
提交回复
热议问题