Beginner5 min readLesson 4 of 50
The cout Object
cout (pronounced "see-out") is used to output values/print text in C++. It is used together with the insertion operator <<.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Output:
Hello World!
New Lines
There are two ways to insert a new line in C++ output:
Method 1: endl
cout << "First line" << endl;
cout << "Second line" << endl;
Method 2: \n (escape character)
cout << "First line\n";
cout << "Second line\n";
Output (both methods):
First line
Second line
Tip: \n is faster than endl because endl also flushes the output buffer. Prefer \n in performance-sensitive code.
Multiple Outputs with <<
You can chain multiple values in a single cout statement:
#include <iostream>
using namespace std;
int main() {
int age = 25;
cout << "I am " << age << " years old." << endl;
cout << "2 + 3 = " << 2 + 3 << endl;
return 0;
}
Output:
I am 25 years old.
2 + 3 = 5
Other Escape Sequences
| Escape | Meaning |
\n | New line |
\t | Tab (horizontal) |
\\ | Backslash |
\" | Double quote |
Exercise
Write a program that outputs three lines: your name, your age, and your city, each on a separate line using \n.
Show Solution
#include <iostream>
using namespace std;
int main() {
cout << "Name: Alex\n";
cout << "Age: 25\n";
cout << "City: Phnom Penh\n";
return 0;
}
Quiz
Which operator is used with cout?
Answer
B) << — the insertion operator sends data to the output stream.
What is the difference between endl and \n?
- A) No difference
- B)
\n only works in strings - C)
endl also flushes the buffer; \n does not - D)
endl adds two newlines
Answer
C) endl flushes the output buffer in addition to adding a newline, making it slower.
Summary
cout is used to print output in C++.
- Use
<< (insertion operator) to send data to cout.
endl or \n creates a new line; \n is faster.
- You can chain multiple values with
<<.