C++: Input and Output in Depth

Last updated: 2026-08-26

In Lesson 03 we briefly used cin and cout, 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 cin and cout.


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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
========== 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.

CPP
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>

CPP
#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:

(2) 2.2 Controlling Output Width (Alignment)

CPP
#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!

CPP
#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:

TEXT 📖 Display only
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().

CPP
#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:

TEXT 📖 Display only
Please enter your full name: John Smith
Hello,John Smith! ← Complete read

(3) 3.3 The Pitfall of Mixing cin and getline

Problem:

CPP
#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

CPP
#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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
========== 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:

TEXT 📖 Display only
========== 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

CPP
#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

TEXT 📖 Display only
#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

Q Why does my program output garbled Chinese characters?
A This is a Windows console Chinese encoding issue. You can add 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.
Q Why do cin and cout need std::? Can I omit it?
A 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.
Q How do I clear the screen?
A Windows: system("cls");, macOS/Linux: system("clear");. But this approach is not portable and not recommended in production — only for temporary use during learning.
Q Why can getline read strings but not int?
A 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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Unit price: 19.99
Quantity:     5
Total: 99.95
💡 Tip: std::fixed + std::setprecision(2) keeps 2 decimal places; std::setw(5) sets the width.



📖 Summary

📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that outputs a multiplication table (1-9) in the following format:
TEXT 📖 Display only
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)

  1. Intermediate (Difficulty ⭐⭐): Write a program that lets the user input:
  2. Product name (may contain spaces, e.g., "iPhone 15 Pro")
  3. Unit price
  4. Quantity

The program calculates the total and outputs formatted:

TEXT 📖 Display only
========== Shopping Receipt ==========
Product name: iPhone 15 Pro
Unit price: 6999.00 yuan
Quantity: 2
Total: 13998.00 yuan
==============================
  1. Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "contact book entry":
  2. Let the user enter 3 contacts' information (name, phone, relationship)
  3. Write the information to a file contacts.txt
  4. Then read from the file and display it

(Hint: use 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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏