In C++, width(n) sets the minimum number of characters that the next value will take when it is written. Shorter values are padded with the fill character, which is a space by default.
Without an argument, width() only tells you the current width. It is the member-function twin of the setw manipulator. Include <iostream> to use it.
This is a member function of std::ios_base. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call width on a stream. With a number it sets the width. Without one it returns the current width.
C++
std::cout.width(8);
std::cout << 42 << '\n'; // " 42"
std::streamsize w = std::cout.width(); // read the width
Call
What it does
std::cout.width(8)
The next output takes at least 8 characters.
std::cout.width()
Returns the current width without changing it.
in.width(4); in >> buf;
For input, reads at most 3 characters into a char array.
The width applies to one item only. After that item, the width goes back to 0.
buf holds four characters, three letters and the end marker.
width(4) tells >> to read at most three characters, so only abc is taken, and the rest stays in the stream.
The width was reset, so it is set again before the second read. That read gives def.
Frequently Asked Questions
width(n) sets the minimum number of characters for the next output. Shorter values are padded. Without an argument it returns the current width.
It is reset to 0 after each formatted output or input. Set it again before each value.
They do the same job. width() is a member call (cout.width(8)). setw() is a manipulator from <iomanip> that fits inside a chain (cout << setw(8) << x).
No. The width is a minimum. A value longer than the width is printed in full.
Use fill(), for example cout.fill('0') pads with zeros. The setfill manipulator does the same inside a chain.