Chapter 5: Input & Output (I/O)
Input & Output (I/O) in C++: Talking to the User Like a Pro!
Hello my wonderful student! 👋 Welcome to one of the most exciting and most used parts of C++ — Input and Output (I/O)!
Up to now, we’ve been printing fixed messages like “Hello, World!”. Today we’re going to make programs that talk back to the user:
- Ask for their name, age, marks, favorite color…
- Read what they type
- Print beautiful, nicely formatted output
We’ll cover everything step-by-step, with lots of live examples, common mistakes, and pro tips that even senior developers use daily.
Let’s dive in!
1. The Three Main I/O Streams
C++ gives us three important streams (think of them as pipes for data):
| Stream | Purpose | When to use | Buffered? |
|---|---|---|---|
| std::cout | Standard Output (normal printing) | Most messages, results, user feedback | Yes |
| std::cin | Standard Input (reading from keyboard) | Get data from user | — |
| std::cerr | Standard Error (error messages) | Print serious errors/warnings | No (immediate) |
Quick rule of thumb (what most pros follow):
- Use cout for normal output
- Use cerr for error messages (red text in many terminals!)
- Use cin to read user input
2. Basic Output with std::cout
We’ve already used it — but let’s see the full power.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> int main() { std::cout << "Hello! How are you today?\n"; std::cout << "My name is " << "Webliance" << " and I love C++!\n"; int age = 25; std::cout << "I am " << age << " years old.\n"; return 0; } |
Newline options — three common ways:
|
0 1 2 3 4 5 6 7 8 |
std::cout << "Line 1\n"; // \n = newline std::cout << "Line 2" << std::endl; // endl = newline + flush buffer std::cout << "Line 3" << '\n'; // same as first, but using char |
Pro tip: std::endl is slightly slower because it flushes the buffer (forces immediate print). In most cases, just use \n — it’s faster and good enough.
3. Reading Input with std::cin
The extraction operator >> reads data from the user.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <string> int main() { std::string name; int age; std::cout << "What is your name? "; std::cin >> name; // reads until space or enter std::cout << "How old are you? "; std::cin >> age; std::cout << "Hello " << name << "! You are " << age << " years old.\n"; return 0; } |
Important limitation of >>: It stops at whitespace (space, tab, enter).
So if user types: Webliance Kumar → name will only get “Webliance” → leftover “Kumar” stays in the input buffer → next cin will read it by mistake!
Solution → Use std::getline() for full lines (see below)
4. Reading Full Lines with std::getline()
Best way to read names, addresses, sentences, etc.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> int main() { std::string fullName; std::string favoriteQuote; std::cout << "Enter your full name: "; std::getline(std::cin, fullName); // reads entire line, including spaces std::cout << "Enter your favorite quote: "; std::getline(std::cin, favoriteQuote); std::cout << "Hello, " << fullName << "!\n"; std::cout << "Your favorite quote is:\n\"" << favoriteQuote << "\"\n"; return 0; } |
Very common mistake & fix:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
int age; std::cout << "Enter age: "; std::cin >> age; // If you do getline right after cin >> std::string name; std::getline(std::cin, name); // ← This will read empty line! (leftover \n) |
Fix – eat the leftover newline:
|
0 1 2 3 4 5 6 7 8 9 10 |
std::cin >> age; std::cin.ignore(); // ignore 1 character (the \n) std::string name; std::getline(std::cin, name); // now works perfectly! |
Even safer version (recommended):
|
0 1 2 3 4 5 6 7 8 |
std::cin >> age; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignores everything until next newline |
(You need to #include <limits> and #include <iostream>)
5. Beautiful & Formatted Output – Manipulators!
C++ has I/O manipulators (from <iomanip>) to make output look professional.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <iomanip> // ← Must include this! #include <string> int main() { double pi = 3.141592653589793; double salary = 125000.75; std::cout << "Default: " << pi << "\n"; // Fixed + precision std::cout << std::fixed << std::setprecision(2); std::cout << "Fixed (2 decimals): " << pi << "\n"; // 3.14 std::cout << "Salary: $" << salary << "\n"; // 125000.75 // Scientific notation std::cout << std::scientific << std::setprecision(4); std::cout << "Scientific: " << pi << "\n"; // 3.1416e+00 // setw() – set width (right-aligned by default) std::cout << "\nTable example:\n"; std::cout << std::left; // left-align std::cout << std::setw(15) << "Name" << std::setw(10) << "Age" << std::setw(12) << "Salary" << "\n"; std::cout << std::setw(15) << "Webliance" << std::setw(10) << 25 << std::setw(12) << 125000.75 << "\n"; return 0; } |
Most useful manipulators:
| Manipulator | Effect |
|---|---|
| std::fixed | Show decimals (not scientific) |
| std::scientific | Show in scientific notation |
| std::setprecision(n) | Show n digits after decimal (with fixed) |
| std::setw(n) | Set field width to n characters |
| std::left / std::right | Align text left or right in field |
| std::setfill(‘*’) | Fill empty space with ‘*’ (or any char) |
6. Using std::cerr for Errors
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> int main() { int age; std::cout << "Enter your age: "; std::cin >> age; if (age < 0) { std::cerr << "Error: Age cannot be negative!\n"; return 1; // exit with error code } std::cout << "You are " << age << " years old.\n"; return 0; } |
In many terminals, cerr appears in red — very useful for debugging!
7. Full Practical Example – Mini Student Record Program
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <iomanip> #include <string> #include <limits> int main() { std::string name; int rollNo; double marks[3]; double total = 0; std::cout << "=== Student Record ===\n\n"; std::cout << "Enter full name: "; std::getline(std::cin, name); std::cout << "Enter roll number: "; std::cin >> rollNo; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Enter marks for 3 subjects:\n"; for (int i = 0; i < 3; ++i) { std::cout << "Subject " << (i+1) << ": "; std::cin >> marks[i]; total += marks[i]; } double average = total / 3.0; // Beautiful formatted output std::cout << "\n" << std::fixed << std::setprecision(2); std::cout << std::left; std::cout << std::setw(20) << "Name:" << name << "\n"; std::cout << std::setw(20) << "Roll No:" << rollNo << "\n"; std::cout << std::setw(20) << "Average Marks:" << average << "\n"; std::string grade = (average >= 90) ? "A+" : (average >= 80) ? "A" : (average >= 70) ? "B" : "C"; std::cout << std::setw(20) << "Grade:" << grade << "\n"; return 0; } |
Your Mini Homework (Try These!)
- Write a program that asks for:
- First name
- Last name
- Age
- Height in cm (use double) Print a nice summary using setw and fixed.
- Create a program that asks for two numbers and prints:
- Sum
- Difference
- Product
- Quotient (with 4 decimal places)
- Make a program that reads a full sentence and prints it in uppercase (hint: you’ll learn string functions soon!).
You’re doing amazing! Now your programs can talk and listen — that’s when they start feeling alive!
Next lesson: Control Structures (if, else, switch, loops) — the real decision-making power!
Any questions? Confused about getline vs cin? Want more formatting examples? Just tell me — your friendly C++ teacher is always here! 🚀
