Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::setw — setting stream field width

std::setw(n), declared in <iomanip>, sets a stream's field width. On output, shorter values are padded and longer values are not truncated. Reapply the width for successive fields because output operations can reset it.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <iomanip>
out << std::setw(n) << value;
in >> std::setw(n) >> value;

std::setw(n) is a manipulator declared in <iomanip>. Used as out << std::setw(n) or in >> std::setw(n), it effectively calls width(n) on that stream. It accepts an int and returns an object of unspecified type, not the width itself. On input, the setting's meaning depends on the extraction operation; it is not a general limit on the number of digits.

On output, the width specifies a minimum field size for operations that honor it. A shorter representation receives fill characters; a longer one is written in full. std::setfill selects the fill character, while std::left and std::right let you align text to the left and right respectively.

Do not treat width as a persistent column setting. Character and character-string insertion operations reset it after use, so put std::setw(n) immediately before each field that needs padding. Even a separator inserted before the intended value can consume the width. Merely setting fill or alignment does not consume it; those settings remain active until changed.

In the example, cat receives two dots on the left, x is not padded, and dog receives two dots on the right. bird remains complete despite width 2. std::setw is defined in the [std.manip] section. The cited document is a working draft, not a frozen C++23 publication.

Examples

#include <iomanip>
#include <iostream>
#include <sstream>

int main() {
    std::ostringstream out;
    out << std::setfill('.') << std::right;
    out << '|' << std::setw(5) << "cat" << '|' << "x" << '|';
    out << std::left << std::setw(5) << "dog" << '|';
    out << std::setw(2) << "bird" << '|';
    std::cout << out.str() << '\n';
}

Result

|..cat|x|dog..|bird|

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources