Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::right — right-align an output field

std::right sets right alignment on an output stream: padding characters appear before the value. The setting persists, while the field width is specified separately, for example with std::setw.

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

Syntax

#include <ios>
std::ios_base& std::right(std::ios_base& str);
// Usage: out << std::right << std::setw(width) << value;

std::right is a manipulator declared in <ios>, used as out << std::right. It calls str.setf(std::ios_base::right, std::ios_base::adjustfield) and returns a reference to the same stream. It replaces the previous setting in the adjustfield group, such as std::left or std::internal, without changing other flag groups.

If the field width exceeds the length of the output representation, fill characters are added before it. std::right itself sets neither the width nor the fill character: use std::setw and std::setfill from <iomanip>, respectively. The width is a minimum, not a limit that truncates text.

Alignment remains set until the flags are changed again. In contrast, inserting a character or a character string resets the field width, so repeat std::setw before each such field that needs padding. Do not confuse the persistent alignment setting with the width of an individual field.

The example sets the fill character to a dot and writes two strings in fields of width 5. The | separators show the field boundaries; the expected result is |..cat|...ox| followed by a newline.

Examples

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

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

Result

|..cat|...ox|

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