C++ Output (cout)
std::cout prints to the console. The output operator << sends a value to it, and several values can be chained in one statement. Unlike C's printf, cout knows the type of each value, so there are no format codes to get wrong.
Printing text and numbers
#include <iostream>
int main() {
int apples = 3, oranges = 8;
std::cout << "Hello " << "World" << "\n";
std::cout << apples << " apples and " << oranges << " oranges\n";
std::cout << "Total: " << apples + oranges << "\n";
return 0;
}Hello World 3 apples and 8 oranges Total: 11
cout does not add spaces or newlines by itself; put them in the text.
Special characters
Escape sequences work inside text: \n new line, \t tab, \" a double quote, \\ a backslash.
#include <iostream>
int main() {
std::cout << "Name\tAge\n";
std::cout << "Asha\t12\n";
std::cout << "She said \"hi\".\n";
return 0;
}Name Age Asha 12 She said "hi".
Decimals
By default cout shows up to six significant digits. std::fixed with std::setprecision(n), from the header iomanip, shows exactly n digits after the decimal point. The setting stays until you change it.
#include <iomanip>
#include <iostream>
int main() {
double pi = 3.14159265;
std::cout << pi << "\n";
std::cout << std::fixed << std::setprecision(2) << pi << "\n";
std::cout << 2.5 << "\n";
return 0;
}3.14159 3.14 2.50
Columns with setw
std::setw(n) makes the next value take at least n characters, moved to the right; std::left moves it to the left. This lines up tables:
#include <iomanip>
#include <iostream>
int main() {
std::cout << std::left << std::setw(10) << "Item" << std::right << std::setw(6) << "Price" << "\n";
std::cout << std::fixed << std::setprecision(2);
std::cout << std::left << std::setw(10) << "Pen" << std::right << std::setw(6) << 1.5 << "\n";
std::cout << std::left << std::setw(10) << "Notebook" << std::right << std::setw(6) << 12.25 << "\n";
return 0;
}Item Price Pen 1.50 Notebook 12.25
C++23 adds std::print, which formats like Python's format: std::println("{} + {} = {}", 2, 3, 5);. Choose C++23 in the editor's Options to use it.
cout or printf?
C++ programs can also use C's printf from cstdio. cout is type-safe: it picks the right format for every value, including your own types once you teach it how (see Operator Overloading). printf is shorter for complex formats. Mixing both in one program works, but pick one style per program for consistency.
endl or \n?
std::endl writes a newline and flushes the output, forcing it out immediately. Flushing is slow when you print thousands of lines, so '\n' is the better default; use std::endl when the text must appear at once, for example before a long calculation.
Practice exercises
- Print a small table of three students and their marks with lined-up columns.
- Print the result of 10 / 3.0 with 4 decimals.
- Print the path
C:\Users\studentexactly as written.