C++ iostream

C++ <iostream>: Input and Output Streams

The <iostream> library is one of the most fundamental headers in C++. It stands for Input/Output Stream and gives your program the ability to interact with the user via the console.

Without it, your C++ program would have no standard way to display text to the screen or read keyboard input!


1. Core iostream Objects

When you include <iostream>, you get access to several important objects:

Basic I/O Example

#include <iostream>
using namespace std;

int main() { int age; cout << "Enter your age: "; // Output cin >> age; // Input cout << "You are " << age << " years old.\n"; return 0; }


2. Common Errors with <iostream>

Working with console inputs can sometimes be tricky for beginners. Here are the most frequent pitfalls:

Error 1: Forgetting the Header

If you try to use cout or cin without #include &lt;iostream&gt;, the compiler will completely reject your code, stating that cout is undeclared.

Error 2: Mixing up Insertion and Extraction Operators

Error 3: Endless Input Loops (Failed State)

If you ask for an int using cin >> age; but the user types "Hello" (a string), the input stream enters a failed state. It will stop accepting new inputs entirely, potentially causing infinite loops if you are inside a while loop. You must clear the error state using cin.clear() to recover!


Exercise

?

Which operator must be used with the `cin` object to take user input?