Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::left — left-align an output field

std::left selects left alignment for formatted stream output. When a field is wider than its value, fill characters appear after the value. The alignment setting remains active until it is changed.

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

Syntax

#include <iomanip>
#include <ios>
#include <ostream>

// Usage with an output stream:
out << std::left << std::setw(width) << value;

std::left is a manipulator declared in <ios>. Writing out << std::left changes the stream's formatting state rather than printing text. The function calls str.setf(std::ios_base::left, std::ios_base::adjustfield) and returns str: it replaces the alignment setting without changing other flag groups.

In a left-aligned output field, fill characters follow the value. Set the width with std::setw(width) and the fill character with std::setfill(c); both manipulators require <iomanip>. Width is a minimum: longer text is not truncated. std::left itself sets neither the width nor the fill character.

Alignment and the fill character remain set until changed. In contrast, inserting a character or character string resets the field width, so repeat std::setw before each such field. std::right replaces left alignment with right alignment. When using a shared stream, remember that changed state also affects later output operations.

The example uses dots to make padding visible. The first two fields demonstrate that std::left persists, and the last demonstrates switching to std::right. You can verify the example locally with -std=c++23. The displayed source was run unchanged in an isolated environment, and its standard output (stdout) matched the expected output exactly. This verification does not attest to production runtime behavior.

Examples

#include <iomanip>
#include <ios>
#include <iostream>

int main() {
    std::cout << std::setfill('.') << std::left;
    std::cout << '|' << std::setw(6) << "cat"
              << '|' << std::setw(6) << "ox" << "|\n";
    std::cout << std::right
              << '|' << std::setw(6) << "cat" << "|\n";
}

Result

|cat...|ox....|
|...cat|

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