C++ Basics: Pad Each Output Field Explicitly with setw
Separate one-field width settings from persistent fill characters in formatted stream output.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as setw-field-padding-demo.cpp:
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0');
std::cout << "One width: " << std::setw(4) << 7 << ' ' << 12 << '\n';
std::cout << "Two widths: " << std::setw(4) << 7 << ' '
<< std::setw(4) << 12 << '\n';
std::cout << "Long value: " << std::setw(4) << 12345 << '\n';
std::cout << std::setfill(' ');
std::cout << "Restored: [" << std::setw(4) << 7 << "]\n";
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic setw-field-padding-demo.cpp -o setw-field-padding-demo &&
./setw-field-padding-demoObserved output:
One width: 0007 12
Two widths: 0007 0012
Long value: 12345
Restored: [ 7]Read the result
The first setw applies to 7 only, leaving 12 unpadded. Setting the width again pads both numbers. A five-digit value remains intact because width is a minimum, not a truncation limit. Restoring the fill character prevents later output from unexpectedly receiving zero padding.
Apply it carefully
For these formatted integer insertions, width resets after each value; the fill character persists. Put setw immediately before the field it belongs to, since another formatted insertion can consume it. Width measures stream character units, not terminal display columns, so it is insufficient for general Unicode table alignment. Negative values may need an explicit alignment policy when padding around a sign.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- setw-field-padding-demo.cpp setw-field-padding-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.