C++ Output
The standard way to print in C++ is the output stream std::cout ("character output") together with the insertion operator <<. You "insert" values into the stream, and they appear on the screen.
Printing text and numbers
You can chain as many << as you like, and mix text with numbers:
#include <iostream>
using namespace std;
int main() {
cout << "Apples: " << 5 << "\n";
cout << "Price: " << 1.25 << " euro\n";
cout << "Total: " << 5 * 1.25 << "\n";
}Apples: 5
Price: 1.25 euro
Total: 6.25
Notice that cout does not add spaces or line breaks automatically. You must write them yourself.
New lines: \n vs endl
There are two ways to end a line:
#include <iostream>
using namespace std;
int main() {
cout << "Line one\n";
cout << "Line two" << endl;
cout << "Line three" << '\n';
}Line one
Line two
Line three
Both start a new line. The difference is that endl also flushes the stream — forces the buffered text out to the screen immediately. Flushing is slow when done thousands of times, so prefer '\n' and use endl only when you really need the output to appear right now.
Escape sequences
Inside a string, a backslash starts an escape sequence — a way to write characters you cannot type directly:
| Sequence | Meaning |
|---|---|
\n |
New line |
\t |
Horizontal tab |
\\ |
A single backslash |
\" |
A double quote |
\' |
A single quote |
#include <iostream>
using namespace std;
int main() {
cout << "Name\tScore\n";
cout << "Ana\t92\n";
cout << "She said \"hi\"\n";
cout << "Path: C:\\Users\\ana\n";
}Name Score
Ana 92
She said "hi"
Path: C:\Users\ana
Tip: For text with many backslashes or quotes, use a raw string literal:
R"(C:\Users\ana)". Everything betweenR"(and)"is taken literally.
Formatting numbers
The <iomanip> header provides manipulators that change how values are printed. The most common ones are fixed with setprecision (decimal places) and setw (minimum width):
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265;
cout << pi << "\n";
cout << fixed << setprecision(2) << pi << "\n";
cout << "[" << setw(6) << 42 << "]\n";
cout << "[" << left << setw(6) << 42 << "]\n";
}3.14159
3.14
[ 42]
[42 ]
By default cout shows up to 6 significant digits. fixed + setprecision(2) stays in effect for all later numbers, while setw only applies to the very next value.
Error output
Besides cout there is std::cerr, the error stream. It is meant for error messages and is not buffered. In a terminal both appear on screen, but they can be redirected separately (for example ./app > out.txt still shows errors).
Test yourself
What does cout << "A" << "B"; print?
- A B
- AB
- A\nB
- A, B
What is the difference between endl and '\n'?
endlalso flushes the stream'\n'does not start a new lineendladds two newlines- There is no difference
Which escape sequence inserts a tab?
- \b
- \t
- \s
- \tab