高级程序设计(C++)


输入输出流:从控制台到文件

计算机学院    杨已彪

yangyibiao@nju.edu.cn

本讲提纲

控制台与字符串

  • 流模型与 iostream

  • 格式化输出

  • >> 与 getline

  • stringstream

文件与自定义类型

  • 文件流与打开模式

  • 文本 vs 二进制

  • 流状态与错误处理

  • 重载 << / >>

本讲目标

能够安全地读写文本文件,并为自定义类型提供一致的输入输出接口。


流:把 I/O 看成字节的流动

输入流

数据从外部(键盘、文件、字符串)流向程序:

键盘/文件 → 缓冲区 → 程序变量

输出流

数据从程序流向外部:

程序变量 → 缓冲区 → 屏幕/文件
流对象的三件事
  1. 方向:输入 / 输出
  2. 来源/目标:控制台、文件、字符串
  3. 状态:成功、失败、文件尾
统一抽象

无论是键盘、文件还是字符串,读写方式都是一样的:用 << / >> 或成员函数。


iostream 的类层次

ios_base istream ostream iostream
常用对象
  • std::cin:标准输入(键盘)

  • std::cout:标准输出(屏幕,带缓冲)

  • std::cerr:标准错误(不带缓冲)

  • std::clog:标准日志(带缓冲)

文件流继承自同样的基类:ifstream / ofstream / fstream;字符串流是 istringstream / ostringstream。


格式化输出

#include <iostream>
#include <iomanip>

double pi = 3.1415926;
int id = 42;

std::cout << std::fixed << std::setprecision(2)
          << pi << "\n";              // 3.14

std::cout << std::setw(6) << id << "\n";    // "    42"
std::cout << std::left << std::setw(6) << id
          << "|\n";                   // "42    |"

std::cout << std::hex << 255 << "\n";       // ff
std::cout << std::setfill('0')
          << std::setw(4) << 7 << "\n";     // 0007
常用操纵符
  • std::fixed / std::scientific

  • std::setprecision(n)

  • std::setw(n)(只影响下一次输出)

  • std::left / std::right

  • std::setfill(c)

  • std::hex / std::dec / std::oct

  • std::boolalpha

状态会保留 std::fixed、std::hex 等会改变流的长期状态;setw 只影响下一次输出。需要时记得恢复。

>> 与 getline:换行符的陷阱

int id;
std::string name;

std::cout << "id: ";
std::cin >> id;                 // 读取 42,留下 '\n'

std::cout << "name: ";
std::getline(std::cin, name);  // 读到空串!

修正:

std::cin >> id;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
                '\n');
std::getline(std::cin, name);
>> 的行为
  • 跳过前导空白(空格、\t、\n)

  • 读到空白或类型不匹配为止

  • 不读取分隔符本身

getline 的行为
  • 读取整行,包含空格

  • 丢弃行尾 \n

  • 遇到流结束或失败时停止

规则

在 >> 之后使用 getline,先清掉残留的换行符;或者统一用 getline + stringstream 解析。


stringstream:在字符串上读写

#include <sstream>
#include <string>

int id = 42;
std::string name = "main.o";

std::ostringstream oss;
oss << id << "," << name << ",2";
std::string line = oss.str();   // "42,main.o,2"

std::istringstream iss(line);
std::string token;
while (std::getline(iss, token, ',')) {
    std::cout << "[" << token << "]";
}
用途
  • 把多个值拼成一行

  • 解析一行中的多个字段

  • 做类型转换(std::stoi 的替代)

  • 单元测试中构造输入

CSV 注意

如果字段本身可能包含逗号或换行,需要转义或使用专门的 CSV 库;教学项目可先约定“标题不含逗号”。


文件流:打开、读写、关闭

#include <fstream>

std::ofstream out("targets.txt");       // 默认 ios::out
if (!out) {
    std::cerr << "cannot open file\n";
    return 1;
}
out << "1 main.o 2\n";
out << "2 util.o 4\n";
out.close();

std::ifstream in("targets.txt");
if (!in) { /* ... */ }

int id, priority;
std::string name;
while (in >> id >> name >> priority) {
    std::cout << id << " " << name << "\n";
}
打开模式
  • std::ios::in:读

  • std::ios::out:写(清空/创建)

  • std::ios::app:追加

  • std::ios::binary:二进制

  • 组合:in | binary

必须检查

文件可能不存在、无权限、磁盘已满。打开后立即检查 if (!in),不要假设一定成功。


文本 vs 二进制

文本方式

out << 1234567;   // 7 个字符
  • 人可读

  • 跨平台较好(注意换行符)

  • 需要解析

  • 浮点数精度/格式可能丢失

二进制方式

int x = 1234567;
out.write(reinterpret_cast<const char*>(&x),
          sizeof(x));
  • 紧凑、读写快

  • 与内存布局绑定

  • 受字节序、类型大小、对齐影响

  • 跨平台/跨编译器不稳定

选择

配置文件、日志、交换格式优先文本;性能敏感且两端环境一致的内部数据才考虑二进制。

以文本方式写出的文件要以文本方式读入;以二进制方式写出的文件要以二进制方式读入。


流状态:判断读写是否成功

状态 含义 检查方式
good 一切正常 if (in)
fail 类型不匹配/格式错误 in.fail()
eof 到达文件尾 in.eof()
bad 严重错误(如磁盘故障) in.bad()
int x;
while (in >> x) {
    // 读取成功才进入循环
}
if (in.eof()) {
    std::cout << "done\n";
} else if (in.fail()) {
    std::cout << "format error\n";
}
经典错误 while (!in.eof()) { in >> x; ... }:文件尾时仍会多执行一次循环,最后一条数据被重复处理。

为 Target 重载 << 与 >>

std::ostream& operator<<(std::ostream& os, const Target& t) {
    return os << t.id() << ' '
              << t.name() << ' '
              << t.priority();
}

std::istream& operator>>(std::istream& is, Target& t) {
    int id, priority;
    std::string name;
    if (is >> id >> name >> priority) {
        t = Target(id, name, priority);
    }
    return is;
}
约定
  • 返回流引用,支持链式

  • 输入失败时不修改对象,或保持对象有效

  • 格式与 operator<< 对应

  • 名称含空格时改用 getline + 分隔符

注意 >> 读取 name 时遇到空格就停;如果名称是 "write report",只会读到 "write"。需要整行读取时用 getline。

主线案例:TargetRepository 的保存与加载

class TargetRepository {
public:
    explicit TargetRepository(std::string path)
        : path_(std::move(path)) {}

    bool save(const std::vector<Target>& targets) const {
        std::ofstream out(path_);
        if (!out) return false;
        for (const Target& t : targets) {
            out << t << '\n';
        }
        return static_cast<bool>(out);
    }

    std::vector<Target> load() const {
        std::vector<Target> targets;
        std::ifstream in(path_);
        if (!in) return targets;
        Target t(0, "", 0);
        while (in >> t) targets.push_back(t);
        return targets;
    }
private:
    std::string path_;
};
设计点
  • 构造时只保存路径,不立即打开文件

  • save 返回 bool,调用方决定如何处理失败

  • load 遇到文件不存在返回空列表

  • 格式与 operator<< / >> 一致

异常 vs 返回码

这里用返回值表示 I/O 失败;也可以抛异常。两种方式都合理,关键是在整个项目中保持一致。


课堂任务 10:任务文件读写

任务

实现 save_targets 与 load_targets:

  • 文件格式:每行 id|name|priority

  • 标题可以包含空格

  • 保存时检查文件是否成功打开

  • 加载时跳过空行与格式错误的行

  • 返回加载到的任务数量

在 main 中保存 3 个任务,再加载并打印。

验收标准
  • 名称含空格也能正确保存/加载

  • 文件不存在时不会崩溃

  • 格式错误行被跳过,不进入死循环

  • 保存后立即读取,内容一致

  • 使用 std::getline + std::stringstream

提示

用 getline(in, line) 读整行,再用 stringstream 按 | 切分;不要用 >> 直接读标题。


任务 10 参考实现

#include <fstream>
#include <sstream>
#include <string>
#include <vector>
bool save_targets(const std::string& path,
                const std::vector<Target>& targets) {
    std::ofstream out(path);
    if (!out) return false;
    for (const Target& t : targets) {
        out << t.id() << '|' << t.name()
            << '|' << t.priority() << '\n';
    }
    return static_cast<bool>(out);
}

std::vector<Target> load_targets(const std::string& path) {
    std::vector<Target> targets;
    std::ifstream in(path);
    if (!in) return targets;

    std::string line;
    while (std::getline(in, line)) {
        if (line.empty()) continue;
        std::istringstream iss(line);
        std::string id_s, name, prio_s;
        if (!std::getline(iss, id_s, '|')) continue;
        if (!std::getline(iss, name, '|')) continue;
        if (!std::getline(iss, prio_s, '|')) continue;
        try {
            int id = std::stoi(id_s);
            int p = std::stoi(prio_s);
            targets.emplace_back(id, name, p);
        } catch (const std::exception&) {
            // 跳过格式错误的行
        }
    }
    return targets;
}
要点
  • getline(in, line) 读整行

  • stringstream 按 | 切分

  • stoi 转换,失败抛异常

  • try/catch 跳过坏行

  • 返回 vector<Target>,由调用方决定后续

更严格的实现会记录错误行号,或返回 expected<vector<Target>, Error>;异常处理单元会讨论。


常见陷阱

输入

  • >> 后直接 getline,读到空串

  • 用 while (!eof()) 导致重复处理最后一条

  • 不检查 cin 失败,变量保持旧值

  • 名称含空格却用 >> 读取

文件/输出

  • 不检查文件是否成功打开

  • 文本写出、二进制读入

  • 忘记 close(析构通常会自动关闭,但错误检查会丢失)

  • 格式状态(hex、fixed)污染后续输出

  • 二进制直接写结构体,跨平台不可读

原则

每次 I/O 后都问一句:“如果失败,程序会怎样?” 文件不存在、格式错误、磁盘满,都是正常世界的一部分。


课堂小测

  1. std::cin >> x 与 std::getline(std::cin, s) 在处理空白字符上有什么不同?
  2. 为什么 while (!in.eof()) { in >> x; ... } 可能重复处理最后一条数据?
  3. 文本方式与二进制方式存储整数 1234567 各占多少字节?各有什么优缺点?
  4. 为自定义类型重载 >> 时,如果读取失败,对象应该处于什么状态?

小结:I/O 是程序的边界

控制台
  • cin / cout / cerr

  • 格式化操纵符

  • >> 与 getline 的边界

文件
  • ifstream / ofstream

  • 打开模式与状态检查

  • 文本优先,二进制慎用

自定义类型
  • operator<< / >> 保持格式对称

  • 输入失败不破坏对象

  • 用 stringstream 解析复杂行

I/O 代码必须假设“外部世界会出错”:文件可能不存在,输入可能格式不对。检查返回值,是所有 I/O 的第一原则。




未完待续