setw() does not affect reading integer fields

那年仲夏 提交于 2020-01-30 05:15:38

问题


I wrote a code like this:

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

But it seems setw() has no effect on reading integers. If so, how we could implement behaviour of %2d of scanf() with istream?


回答1:


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.



来源:https://stackoverflow.com/questions/38920767/setw-does-not-affect-reading-integer-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!