Basic formatting helps you control how text and numbers appear on the screen. It makes output easier to read and understand.
0
0
Basic formatting in C++
Introduction
When you want to show numbers with a fixed number of decimal places.
When you want to align text or numbers in columns.
When you want to add spaces or fill characters to make output look neat.
When you want to display data in a table-like format.
When you want to format dates, times, or currency values.
Syntax
C++
#include <iostream> #include <iomanip> std::cout << std::setw(width) << value; std::cout << std::setprecision(n) << value; std::cout << std::fixed << value; std::cout << std::left << std::right << std::internal << value;
#include <iomanip> is needed for formatting functions like setw and setprecision.
setw(width) sets the width of the next output field.
Examples
This prints the number 123 right-aligned in a field 10 characters wide.
C++
#include <iostream> #include <iomanip> int main() { std::cout << std::setw(10) << 123 << "\n"; return 0; }
This prints the number 3.14159 as 3.14 with two decimal places.
C++
#include <iostream> #include <iomanip> int main() { double pi = 3.14159; std::cout << std::fixed << std::setprecision(2) << pi << "\n"; return 0; }
This prints a simple table with left-aligned names in a 10-character wide column.
C++
#include <iostream> #include <iomanip> int main() { std::cout << std::left << std::setw(10) << "Name" << "Age" << "\n"; std::cout << std::left << std::setw(10) << "Alice" << 30 << "\n"; return 0; }
Sample Program
This program prints a small price list with item names left-aligned and prices right-aligned with two decimal places.
C++
#include <iostream> #include <iomanip> int main() { std::cout << std::left << std::setw(10) << "Item" << std::right << std::setw(8) << "Price" << "\n"; std::cout << std::left << std::setw(10) << "Apple" << std::right << std::setw(8) << std::fixed << std::setprecision(2) << 0.99 << "\n"; std::cout << std::left << std::setw(10) << "Banana" << std::right << std::setw(8) << std::fixed << std::setprecision(2) << 1.25 << "\n"; return 0; }
OutputSuccess
Important Notes
Formatting affects only the next output or until changed again.
Use std::fixed to show decimal numbers in fixed-point notation.
Use std::left, std::right, or std::internal to control text alignment.
Summary
Basic formatting controls how output looks on the screen.
Use setw to set width and setprecision to control decimal places.
Alignment and fixed decimal formatting make output clearer and easier to read.