cout: Printing in C++
Print with cout and <<, end lines with endl, and show true/false with boolalpha.
C++ · beginner · 5 min · 8 steps · free
What you'll learn
- Print values with cout <<
- Chain several values
- Use endl and boolalpha
cout_basics.cpp
#include <iostream>
using namespace std;
int main() {
int apples = 3;
double price = 0.5;
bool fresh = true;
cout << "Apples: " << apples << endl;
cout << "Cost: " << apples * price << endl;
cout << boolalpha << "Fresh? " << fresh << endl;
return 0;
}
Step by step
- An int on the stack.
price is created on the stack with the value 0.5.fresh is created on the stack with the value true.- cout << sends each value to the output in turn; endl ends the line.
- Expressions are worked out first: 3 × 0.5 = 1.5.
- boolalpha prints bools as true/false instead of 1/0.
- The method returns
0. - Three lines printed. cout works out each type itself, no format codes needed.
Common mistakes
- Forgetting << between values
Best practices
- Prefer cout to printf in C++: it checks types for you
Key takeaways
- cout << value prints.
- << can be chained.
- endl ends a line; boolalpha prints true/false.
Check yourself
cout << "a" << 1 << endl prints?
Answer: a1 and a new line. No spaces are added.
Without boolalpha, true prints as?
Answer: 1. bool is a number by default.
References →
More in C++ Basics