Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setw() does not affect reading integer fields

Tags:

c++

stl

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?

like image 824
E. Vakili Avatar asked Aug 12 '16 14:08

E. Vakili


People also ask

What does SETW () do in C++?

In simple terms, the setw C++ function helps set the field width used for output operations. The function takes member width as an argument and needs a stream where this field has to be manipulated or inserted. The function also sets the width parameter of the stream in or stream out exactly n times.

Which has to be used to use SETW function?

The setw() method of iomanip library in C++ is used to set the ios library field width based on the width specified as the parameter to this method. Parameters: This method accepts n as a parameter which is the integer argument corresponding to which the field width is to be set.


1 Answers

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.

like image 177
Bathsheba Avatar answered Oct 07 '22 22:10

Bathsheba