C++: Input and Output in Depth
Last updated: 2026-08-26
In Lesson 03 we briefly used
cinandcout, but that was just the tip of the iceberg.In real scenarios, you need to handle strings with spaces, control decimal places, and make output more presentable...
In this lesson, we'll dive deep into all the capabilities of
cinandcout.
1. Advanced Usage of cout
(1) 1.1 Escape Characters
Some characters can't be typed directly (like newline, Tab), so they need to be represented using escape characters.
| Escape Character | Meaning | Example |
|---|---|---|
\n |
Newline | std::cout << "Hello\nWorld"; |
\t |
Tab | std::cout << "Name:\tMOTO"; |
\\ |
Backslash itself | std::cout << "C:\\Users\\MOTO"; |
\" |
Double quote | std::cout << "He said \"Hi\""; |
\0 |
Null character (string terminator) | (Covered later) |
Example: Formatted output with escape characters (Difficulty ⭐)
▶ Example 2: Basic Programming Practice (Difficulty ⭐)
#include <iostream>
int main() {
std::cout << "========== Report Card ==========\n";
std::cout << "Name: \tMOTO\n";
std::cout << "Age: \t35\n";
std::cout << "Score: \t92.5\n";
std::cout << "===================\n";
return 0;
}
Output:
========== Report Card ==========
Name: MOTO
Age: 35
Score: 92.5
===================
(2) 1.2 endl vs \n
| Notation | Effect | Performance |
|---|---|---|
std::endl |
Outputs newline + flushes the buffer | Slow (flushes every time) |
"\n" |
Only outputs newline | Fast (recommended) |
💡 Recommendation: Unless you explicitly need to flush the buffer, use "\n" instead of std::endl.
std::cout << "Hello" << std::endl; // Newline + flush (slow)
std::cout << "Hello\n"; // Newline only (fast, recommended)
2. Formatted Output with cout
(1) 2.1 Controlling Decimal Places
By default, cout automatically chooses the format for floating-point output (e.g., 3.14159 or 3.14). But sometimes you need a fixed number of decimal places (e.g., displaying a price like $19.99).
Requires #include <iomanip>
#include <iostream>
#include <iomanip> // Must include this header
int main() {
double pi = 3.141592653589793;
std::cout << "Default: " << pi << std::endl;
// Fixed decimal places (2 digits)
std::cout << std::fixed << std::setprecision(2);
std::cout << "2 decimal places: " << pi << std::endl;
// Restore default
std::cout.unsetf(std::ios::fixed);
std::cout << std::setprecision(6); // Restore default precision
std::cout << "Restored default: " << pi << std::endl;
return 0;
}
💡 Key points:
std::fixed— Use fixed decimal format (no scientific notation)std::setprecision(n)— Set precision (when combined withfixed, this means n decimal places)
(2) 2.2 Controlling Output Width (Alignment)
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::left; // Left-align
std::cout << std::setw(10) << "Name" << std::setw(5) << "Age" << std::endl;
std::cout << std::setw(10) << "MOTO" << std::setw(5) << 35 << std::endl;
std::cout << std::setw(10) << "Alice" << std::setw(5) << 20 << std::endl;
return 0;
}
| Manipulator | Effect |
|---|---|
std::setw(n) |
Set the width of the next output to n characters |
std::left |
Left-align |
std::right |
Right-align (default) |
std::setfill(c) |
Set the fill character (default is space) |
3. Advanced Usage of cin
(1) 3.1 cin's Pitfall: Stops at Spaces
cin >> stops reading a string when it encounters a space!
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Please enter your full name (e.g., John Smith): ";
std::cin >> name;
std::cout << "Hello," << name << "!" << std::endl;
return 0;
}
Run result:
Please enter your full name (e.g., John Smith): John Smith
Hello,John! ← Only read "John", "Smith" was discarded
(2) 3.2 Using getline to Read an Entire Line
To read an entire line including spaces, use std::getline().
#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "Please enter your full name: ";
std::getline(std::cin, fullName); // Read entire line (including spaces)
std::cout << "Hello," << fullName << "!" << std::endl;
return 0;
}
Run result:
Please enter your full name: John Smith
Hello,John Smith! ← Complete read
(3) 3.3 The Pitfall of Mixing cin and getline
Problem:
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cout << "Please enter your age: ";
std::cin >> age;
std::cout << "Please enter your name: ";
std::getline(std::cin, name); // ❌ This line gets skipped!
std::cout << "Age: " << age << ",Name: " << name << std::endl;
return 0;
}
Reason: After cin >> age reads the integer, a newline character \n is left in the input buffer. When getline sees \n, it thinks the user entered an empty line and returns immediately.
Solution: Use cin.ignore() to discard the newline character
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cout << "Please enter your age: ";
std::cin >> age;
std::cin.ignore(); // Discard the newline character
std::cout << "Please enter your name: ";
std::getline(std::cin, name); // ✅ Now it reads correctly
std::cout << "Age: " << age << ",Name: " << name << std::endl;
return 0;
}
💡 Golden rule: If you use cin >> first and then getline, remember to add cin.ignore().
4. Practice: User Information Registration Form
▶ Example 1: User Information Registration (Difficulty ⭐⭐)
#include <iostream>
#include <string>
#include <iomanip>
int main() {
std::string name, address;
int age;
double salary;
std::cout << "========== User Information Registration ==========\n";
std::cout << "Please enter your name: ";
std::getline(std::cin, name);
std::cout << "Please enter your age: ";
std::cin >> age;
std::cin.ignore(); // Discard newline character
std::cout << "Please enter your address: ";
std::getline(std::cin, address);
std::cout << "Please enter your monthly salary: ";
std::cin >> salary;
// Output registration form
std::cout << "\n========== Registration Result ==========\n";
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << " years old" << std::endl;
std::cout << "Address: " << address << std::endl;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Monthly salary: " << salary << " yuan" << std::endl;
std::cout << "==============================\n";
return 0;
}
Output:
========== User Information Registration ==========
Please enter your name:
Please enter your age:
Please enter your address:
Please enter your monthly salary:
========== Registration Result ==========
Name:
Age: years old
Address:
Monthly salary: yuan
==============================
Run result:
========== User Information Registration ==========
Please enter your name: MOTO
Please enter your age: 35
Please enter your address: Meijia Vocational College, Xiaogan, Hubei
Please enter your monthly salary: 15000
========== Registration Result ==========
Name: MOTO
Age: 35 years old
Address: Meijia Vocational College, Xiaogan, Hubei
Monthly salary: 15000.00 yuan
==============================
5. Introduction to File I/O (Optional)
Besides reading from the keyboard and writing to the screen, C++ can also read data from files and write data to files.
(1) 5.1 Writing to a File
#include <iostream>
#include <fstream> // File stream header
int main() {
std::ofstream outFile("output.txt"); // Create output file stream
if (!outFile) {
std::cout << "Cannot open file!" << std::endl;
return 1;
}
outFile << "Hello, File!" << std::endl;
outFile << "This is the content written to the file." << std::endl;
outFile.close(); // Close the file
std::cout << "Write successful!" << std::endl;
return 0;
}
After running, an output.txt file will be generated in the program's directory.
(2) 5.2 Reading from a File
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("output.txt"); // Create input file stream
if (!inFile) {
std::cout << "Cannot open file!" << std::endl;
return 1;
}
std::string line;
while (std::getline(inFile, line)) {
std::cout << "Read: " << line << std::endl;
}
inFile.close();
return 0;
}
💡 Tip: File I/O is a big topic — this is just a brief introduction. There will be a dedicated lesson covering it in depth later.
❓ FAQ
system("chcp 65001"); at the beginning of your program to switch to UTF-8 encoding, or change the console font to "NSimSun". macOS/Linux usually doesn't have this issue.cin/cout are defined in the std namespace. You can use using namespace std; to avoid writing std::, but it's not recommended — it can cause naming conflicts. It's recommended to always write std::cin, std::cout.system("cls");, macOS/Linux: system("clear");. But this approach is not portable and not recommended in production — only for temporary use during learning.getline can only read strings. To read integers, use cin >>. If you want to read an entire line and then parse it as an integer, use std::stoi(line) to convert a string to an integer.▶ Example 3: Formatted Output (Difficulty ⭐)
#include <iostream>
#include <iomanip>
int main() {
double price = 19.99;
int quantity = 5;
std::cout << "Unit price: " << std::fixed << std::setprecision(2) << price << std::endl;
std::cout << "Quantity: " << std::setw(5) << quantity << std::endl;
std::cout << "Total: " << price * quantity << std::endl;
return 0;
}
Output:
Unit price: 19.99
Quantity: 5
Total: 99.95
std::fixed + std::setprecision(2) keeps 2 decimal places; std::setw(5) sets the width.
coutuses escape characters (\n,\t) to control formatting- Use
std::fixed+std::setprecision(n)to control decimal places - Use
std::setw(n)to control output width (alignment) cin >>stops reading strings at spaces; usegetlineto read entire lines- When mixing
cin >>andgetline, remember to addcin.ignore()to discard the newline character - File I/O requires
#include <fstream>
📖 Summary
- std::cin: Standard input stream
- std::cout: Standard output stream
- std::cerr: Standard error stream (unbuffered)
- Formatting:
std::setw,std::setprecision, etc.
📝 Exercises
- Basic (Difficulty ⭐): Write a program that outputs a multiplication table (1-9) in the following format:
1 x 1 = 1
1 x 2 = 2 2 x 2 = 4
1 x 3 = 3 2 x 3 = 6 3 x 3 = 9
...
(Hint: use \t for alignment and nested loops)
- Intermediate (Difficulty ⭐⭐): Write a program that lets the user input:
- Product name (may contain spaces, e.g., "iPhone 15 Pro")
- Unit price
- Quantity
The program calculates the total and outputs formatted:
========== Shopping Receipt ==========
Product name: iPhone 15 Pro
Unit price: 6999.00 yuan
Quantity: 2
Total: 13998.00 yuan
==============================
- Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "contact book entry":
- Let the user enter 3 contacts' information (name, phone, relationship)
- Write the information to a file
contacts.txt - Then read from the file and display it
(Hint: use ofstream for writing, ifstream for reading)
- cout uses << for output, supports escape characters (\n, \t)
- Formatted output: fixed/setprecision for decimals, setw for width
- cin uses >> for input, stops at spaces
- getline reads entire line of string; add cin.ignore() when mixing with cin
- File I/O: ofstream for writing, ifstream for reading
10. 🚀 Next Step
Now that you've learned input and output, next we'll learn conditional statements (if-else) (Lesson 06) — enabling programs to make decisions and execute different code based on different conditions.