Introduction to iostream: std::cout, std::cin, and std::endl

The iostream Library

The iostream library provides input and output functionality:

#include <iostream>

Output with std::cout

std::cout (console output) sends data to the screen:

Basic Output

std::cout << "Hello, World!";
std::cout << 42;
std::cout << 3.14159;

Chaining Output

Use multiple << operators to output several things:

std::cout << "The answer is " << 42 << " exactly.";

Variables in Output

int age = 25;
string name = "Alice";
std::cout << "Hello " << name << ", you are " << age << " years old.";

Input with cin

cin (console input) reads data from the keyboard:

Basic Input

int age;
std::cout << "Enter your age: ";
cin >> age;

Multiple Inputs

int x, y;
std::cout << "Enter two numbers: ";
cin >> x >> y;  // User can type: 10 20

String Input

string name;
std::cout << "Enter your name: ";
cin >> name;    // Reads until whitespace

Line Endings with std::endl

std::endl creates a new line and flushes the output buffer:

std::cout << "First line" << std::endl;
std::cout << "Second line" << std::endl;

Alternative: \n

You can also use \n for newlines:

std::cout << "First line\n";
std::cout << "Second line\n";

Formatting Output

Spacing

std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << " years" << std::endl;

Multiple Lines

std::cout << "Welcome to our program!" << std::endl;
std::cout << "Please enter your information:" << std::endl;
std::cout << std::endl;  // Blank line

Common Patterns

Prompt and Input

std::cout << "Enter value: ";
cin >> value;

Calculate and Display

int result = a + b;
std::cout << a << " + " << b << " = " << result << std::endl;