Topic 4 of 83
Output (cout)
Overview
Outputting data to the console is essential for interacting with users and debugging. C++ uses `std::cout` (character output stream) along with the insertion operator `<<` to display text.
Syntax
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl; // endl adds a newline and flushes the stream
cout << "Next line\n"; // \n adds a newline (faster as it doesn't flush)
return 0;
}Common Pitfalls
- Forgetting to `#include <iostream>`, resulting in a 'cout was not declared' error.
- Using the wrong direction for operators (using `>>` instead of `<<` with cout).
Interview Tips
- Explain the difference between 'std::endl' and '\n'. 'endl' inserts a newline AND flushes the output buffer, which can slow down performance in loops. '\n' only inserts a newline.
- Discuss why 'using namespace std;' is considered bad practice in header files (namespace pollution).
Real-World Example
Chaining output streams to print multiple variables.
example
cpp
#include <iostream>
using namespace std;
int main() {
int score = 100;
string name = "Alice";
// Chaining the insertion operator
cout << "Player: " << name << " | Score: " << score << "\n";
return 0;
}