Ready to practice?
Sign up to access interactive coding exercises and track your progress.
Back to C++ Programming Fundamentals
Lesson 8 of 15
Beginner
45 minutes
Introduction to iostream: std::cout, std::cin, and std::endl
Master basic input and output operations using std::cout and std::cin.
Prerequisites
Variable assignment and initialization
Not completed
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;
Introduction to iostream: std::cout, std::cin, and std::endl - Quiz
Test your understanding of the lesson.
15 questions
10 minutes
60% to pass
Practice Exercises
Input and Output with iostream
Practice using std::cout for output and std::cin for input.
Easy
3 hints available
Lesson Discussion
Share your thoughts and questions