C++ Stream Formatting
Stream formatting controls how values look when a program prints them. A program can set field widths, alignment, and the number of decimal places.
Padding a number column
Each number sits in a field six characters wide. Spaces pad the front of each number, so the right edges line up.
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setw(6) << 42 << "\n";
std::cout << std::setw(6) << 7 << "\n";
std::cout << std::setw(6) << 123 << "\n";
return 0;
}Fixed decimal places
std::fixed and std::setprecision(2) are set once here. Each number then prints with two decimal places.
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::fixed << std::setprecision(2);
std::cout << 3.14159 << "\n";
std::cout << 2.5 << "\n";
std::cout << 10.0 << "\n";
return 0;
}Text aligned to the left
std::left puts each word at the start of a field eight characters wide. The count follows the padded field on the same line.
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::left << std::setw(8) << "Pen" << 3 << "\n";
std::cout << std::left << std::setw(8) << "Notebook" << 5 << "\n";
return 0;
}Formatting stays set
std::fixed is set once at the top here. A plain value printed later still shows two decimal places.
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::fixed << std::setprecision(2);
std::cout << 1.5 << "\n";
std::cout << 2.5 * 2 << "\n";
return 0;
}Example
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::fixed << std::setprecision(2);
std::cout << std::left << std::setw(10) << "Pen" << 1.5 << "\n";
std::cout << std::left << std::setw(10) << "Notebook" << 3.25 << "\n";
std::cout << std::left << std::setw(10) << "Ruler" << 2.0 << "\n";
return 0;
}Key points
- The <iomanip> header gives a program the formatting tools of this lesson.
- std::setw sets the width of the field for the next value.
- A value narrower than its field is padded with spaces.
- std::fixed prints decimal numbers with a set number of decimal places.
- std::setprecision sets how many decimal places std::fixed shows.
- std::left aligns a value to the left of its field, and std::right aligns it to the right.
In this example, std::fixed and std::setprecision(2) print every price with two decimal places. Each name sits in a left-aligned field ten characters wide. The three rows print as one aligned price table.
Note
std::setw applies to one value only, while std::fixed and std::left stay set until they are changed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A program sets std::fixed and std::setprecision(2). What does the value 2.5 print as?