Output (cout)
Overview
If a program runs but doesn't output anything, it's virtually useless to the user. C++ uses a powerful concept called 'Streams' to handle data. To output text to the terminal (the standard character output stream), we use std::cout.
The data is pushed into the cout stream using the 'Insertion Operator' (<<). Think of << as a conveyor belt pushing your text into the terminal screen. To start a new line, C++ provides std::endl (End Line) or the classical escape character \n.
Syntax
#include <iostream>
using namespace std;
int main() {
// 1. Basic Output
cout << "Welcome to C++!" << endl;
// 2. Chaining multiple outputs together
int age = 25;
cout << "I am " << age << " years old.\n";
return 0;
}Common Pitfalls
- Forgetting to
#include <iostream>. If you forget this, the compiler has no idea whatcoutis and will throw an error. - Mixing up the insertion (
<<) and extraction (>>) operators.coutalways uses<<(pointing data OUT to the terminal).cinalways uses>>(pulling data IN from the user).
Interview Questions
std::endl and the \n character?Both move the cursor to a new line. However, std::endl also strictly flushes the output buffer (forcing the OS to physically draw the text to the screen immediately). Flushing is highly expensive. If you use endl inside a loop running 100,000 times, it will drastically slow down your program compared to \n.
using namespace std;?It causes 'Namespace Pollution'. The std namespace contains thousands of functions. If you include it globally, and then create your own function named count() or find(), it will violently conflict with the standard library's versions, causing catastrophic compilation ambiguity.
Real-World Example
The modern, professional way to use cout without polluting the global namespace.
#include <iostream>
int main() {
// We explicitly prefix standard tools with 'std::'
// This is universally considered Best Practice in enterprise C++.
std::cout << "Secure output!" << '\n';
return 0;
}Check Your Knowledge
Test your understanding of Output (cout) with these quick questions.