C++: 输入输出详解
最后更新:2026-08-26
第03课我们简单用过
cin和cout,但那只是冰山一角。真实场景中,你需要处理带空格的字符串、控制小数位数、让输出更美观……
这一课,我们来深挖
cin和cout的所有用法。
1. cout 的进阶用法
(1) 1.1 转义字符
有些字符不能直接敲出来(比如回车、Tab),需要用转义字符表示。
| 转义字符 | 含义 | 示例 |
|---|---|---|
\n |
换行 | std::cout << "Hello\nWorld"; |
\t |
制表符(Tab) | std::cout << "Name:\tMOTO"; |
\\ |
反斜杠本身 | std::cout << "C:\\Users\\MOTO"; |
\" |
双引号 | std::cout << "He said \"Hi\""; |
\0 |
空字符(字符串结束符) | (后面会学) |
示例:用转义字符格式化输出(难度⭐)
▶ 示例 2:基础编程实践(难度⭐)
#include <iostream>
int main() {
std::cout << "========== 成绩单 ==========\n";
std::cout << "姓名:\tMOTO\n";
std::cout << "年龄:\t35\n";
std::cout << "成绩:\t92.5\n";
std::cout << "===================\n";
return 0;
}
输出:
========== 成绩单 ==========
姓名: MOTO
年龄: 35
成绩: 92.5
===================
(2) 1.2 endl vs \n
| 写法 | 作用 | 性能 |
|---|---|---|
std::endl |
输出换行 + 刷新缓冲区 | 慢(每次都刷新) |
"\n" |
只输出换行 | 快(推荐) |
💡 建议: 除非你明确需要刷新缓冲区,否则用 "\n" 而不是 std::endl。
std::cout << "Hello" << std::endl; // 换行 + 刷新(慢)
std::cout << "Hello\n"; // 只换行(快,推荐)
2. cout 的格式化输出
(1) 2.1 控制小数位数
默认情况下,cout 输出浮点数时会根据值自动选择格式(如 3.14159 或 3.14)。但有时你需要固定小数位数(比如显示价格 $19.99)。
需要 #include <iomanip>
#include <iostream>
#include <iomanip> // 必须引入这个头文件
int main() {
double pi = 3.141592653589793;
std::cout << "默认:" << pi << std::endl;
// 固定小数位数(2位)
std::cout << std::fixed << std::setprecision(2);
std::cout << "保留2位:" << pi << std::endl;
// 恢复默认
std::cout.unsetf(std::ios::fixed);
std::cout << std::setprecision(6); // 恢复默认精度
std::cout << "恢复默认:" << pi << std::endl;
return 0;
}
💡 重点:
std::fixed— 用固定小数格式(不用科学计数法)std::setprecision(n)— 设置精度(配合fixed就是保留 n 位小数)
(2) 2.2 控制输出宽度(对齐)
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::left; // 左对齐
std::cout << std::setw(10) << "姓名" << std::setw(5) << "年龄" << 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;
}
| 操纵符 | 作用 |
|---|---|
std::setw(n) |
设置下一个输出的宽度为 n 个字符 |
std::left |
左对齐 |
std::right |
右对齐(默认) |
std::setfill(c) |
设置填充字符(默认是空格) |
3. cin 的进阶用法
(1) 3.1 cin 的缺陷:遇到空格就停止
cin >> 读取字符串时,遇到空格就会停止!
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "请输入你的全名(如 John Smith):";
std::cin >> name;
std::cout << "你好," << name << "!" << std::endl;
return 0;
}
运行效果:
请输入你的全名(如 John Smith):John Smith
你好,John! ← 只读取了 "John","Smith" 被丢掉了
(2) 3.2 用 getline 读取整行
要读取带空格的整行,需要用 std::getline()。
#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "请输入你的全名:";
std::getline(std::cin, fullName); // 读取整行(包括空格)
std::cout << "你好," << fullName << "!" << std::endl;
return 0;
}
运行效果:
请输入你的全名:John Smith
你好,John Smith! ← 完整读取
(3) 3.3 cin 和 getline 混用的坑
问题:
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cout << "请输入你的年龄:";
std::cin >> age;
std::cout << "请输入你的名字:";
std::getline(std::cin, name); // ❌ 这行会被跳过!
std::cout << "年龄:" << age << ",名字:" << name << std::endl;
return 0;
}
原因: cin >> age 读取整数后,会留下一个换行符 \n 在输入缓冲区。getline 一看到 \n 就以为用户输入了空行,直接返回了。
解决方法:用 cin.ignore() 丢弃换行符
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cout << "请输入你的年龄:";
std::cin >> age;
std::cin.ignore(); // 丢弃换行符
std::cout << "请输入你的名字:";
std::getline(std::cin, name); // ✅ 现在能正常读取了
std::cout << "年龄:" << age << ",名字:" << name << std::endl;
return 0;
}
💡 黄金法则: 如果先用了 cin >>,后面要用 getline,记得加 cin.ignore()。
4. 实战:用户信息登记表
▶ 示例 1:用户信息登记(难度⭐⭐)
#include <iostream>
#include <string>
#include <iomanip>
int main() {
std::string name, address;
int age;
double salary;
std::cout << "========== 用户信息登记 ==========\n";
std::cout << "请输入姓名:";
std::getline(std::cin, name);
std::cout << "请输入年龄:";
std::cin >> age;
std::cin.ignore(); // 丢弃换行符
std::cout << "请输入地址:";
std::getline(std::cin, address);
std::cout << "请输入月薪:";
std::cin >> salary;
// 输出登记表
std::cout << "\n========== 登记结果 ==========\n";
std::cout << "姓名:" << name << std::endl;
std::cout << "年龄:" << age << " 岁" << std::endl;
std::cout << "地址:" << address << std::endl;
std::cout << std::fixed << std::setprecision(2);
std::cout << "月薪:" << salary << " 元" << std::endl;
std::cout << "==============================\n";
return 0;
}
输出:
========== 用户信息登记 ==========
请输入姓名:
请输入年龄:
请输入地址:
请输入月薪:
========== 登记结果 ==========
姓名:
年龄: 岁
地址:
月薪: 元
==============================
运行效果:
========== 用户信息登记 ==========
请输入姓名:MOTO
请输入年龄:35
请输入地址:湖北孝感美珈职业学院
请输入月薪:15000
========== 登记结果 ==========
姓名:MOTO
年龄:35 岁
地址:湖北孝感美珈职业学院
月薪:15000.00 元
==============================
5. 文件操作初步(选学)
除了从键盘输入、向屏幕输出,C++ 还可以从文件读取数据、向文件写入数据。
(1) 5.1 写入文件
#include <iostream>
#include <fstream> // 文件流头文件
int main() {
std::ofstream outFile("output.txt"); // 创建输出文件流
if (!outFile) {
std::cout << "无法打开文件!" << std::endl;
return 1;
}
outFile << "Hello, File!" << std::endl;
outFile << "这是写入文件的内容。" << std::endl;
outFile.close(); // 关闭文件
std::cout << "写入成功!" << std::endl;
return 0;
}
运行后,会在程序所在目录生成一个 output.txt 文件。
(2) 5.2 读取文件
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("output.txt"); // 创建输入文件流
if (!inFile) {
std::cout << "无法打开文件!" << std::endl;
return 1;
}
std::string line;
while (std::getline(inFile, line)) {
std::cout << "读取到:" << line << std::endl;
}
inFile.close();
return 0;
}
💡 提示: 文件操作是很大的话题,这里只是初步介绍。后面会有专门的课程深入讲解。
❓ 常见问题
system("chcp 65001"); 切换到 UTF-8 编码,或把控制台字体改成"新宋体"。macOS/Linux 通常没有此问题。cin/cout 定义在 std 命名空间里。可用 using namespace std; 避免写 std::,但不推荐——可能引发命名冲突。推荐始终写 std::cin、std::cout。system("cls");,macOS/Linux 用 system("clear");。但此写法不可移植,实际项目中不推荐,学习阶段可临时使用。getline 只能读取字符串。要读取整数后用 cin >>。如果要读取整行再解析成整数,可用 std::stoi(line) 把字符串转为整数。▶ 示例 3:格式化输出(难度⭐)
#include <iostream>
#include <iomanip>
int main() {
double price = 19.99;
int quantity = 5;
std::cout << "商品单价:" << std::fixed << std::setprecision(2) << price << std::endl;
std::cout << "购买数量:" << std::setw(5) << quantity << std::endl;
std::cout << "总价:" << price * quantity << std::endl;
return 0;
}
输出:
商品单价:19.99
购买数量: 5
总价:99.95
std::fixed + std::setprecision(2) 保留2位小数,std::setw(5) 设置宽度。
cout用转义字符(\n、\t)控制格式- 用
std::fixed+std::setprecision(n)控制小数位数 - 用
std::setw(n)控制输出宽度(对齐) cin >>读取字符串时遇到空格就停止,用getline读取整行cin >>和getline混用时,记得加cin.ignore()丢弃换行符- 文件操作需要
#include <fstream>
📖 小节
- std::cin:标准输入流
- std::cout:标准输出流
- std::cerr:标准错误流(无缓冲)
- 格式化:
std::setw、std::setprecision等
📝 作业
- 基础题 (Difficulty ⭐): 编写一个程序,输出以下格式的乘法表(1-9):
1 x 1 = 1
1 x 2 = 2 2 x 2 = 4
1 x 3 = 3 2 x 3 = 6 3 x 3 = 9
...
(提示:用 \t 对齐,用两层循环)
- 进阶题 (Difficulty ⭐⭐): 编写一个程序,让用户输入:
- 商品名称(可能带空格,如 "iPhone 15 Pro")
- 单价
- 数量
程序计算总价,并格式化输出:
========== 购物小票 ==========
商品名称:iPhone 15 Pro
单价:6999.00 元
数量:2
总价:13998.00 元
==============================
- 挑战题 (Difficulty ⭐⭐⭐): 编写一个程序,实现"通讯录录入":
- 让用户输入 3 个联系人的信息(姓名、电话、关系)
- 把信息写入文件
contacts.txt - 然后从文件读取并显示出来
(提示:用 ofstream 写入,ifstream 读取)
- cout 用 << 输出,支持转义字符(\n、\t)
- 格式化输出:fixed/setprecision 控制小数,setw 控制宽度
- cin 用 >> 输入,遇到空格停止
- getline 读取整行字符串,与 cin 混用时加 cin.ignore()
- 文件操作:ofstream 写入、ifstream 读取
6. 🚀 下一步
学会了输入输出,接下来我们学习 条件判断(if-else)(第06课)—— 让程序能做决策,根据不同情况执行不同代码。