0Pricing
C++ Academy · 课时

错误处理与状态

检查流状态

错误处理与状态 是 CoddyKit 上的免费 C++ Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C++ Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C++ Academy 课程共包含 4 节课。

流状态位

每个流都会使用状态标志跟踪自身的状态:

  • goodbit:一切正常。
  • eofbit:已到达文件末尾。
  • failbit:逻辑错误(格式不正确)。
  • badbit:严重的输入/输出错误。
#include <iostream>
#include <fstream>

int main() {
    std::ifstream in("missing_98765.txt");
    std::cout << std::boolalpha << "good: " << in.good() << '\n';
    return 0;
}

测试流

流可以转换为 bool:可用时为 true。if (!in) 可以简洁地检测失败。

#include <iostream>
#include <fstream>

int main() {
    std::ifstream in("nope_55555.txt");
    if (!in) std::cout << "stream not usable\n";
    else std::cout << "ok\n";
    return 0;
}

good、eof、fail、bad

每个标志都有对应的查询方法:good()、eof()、fail() 和 bad()。

#include <iostream>
#include <sstream>

int main() {
    std::istringstream s("abc");
    int x;
    s >> x; // fails: not a number
    std::cout << std::boolalpha;
    std::cout << "fail: " << s.fail() << '\n';
    std::cout << "bad: " << s.bad() << '\n';
    return 0;
}

提取失败

当 >> 无法解析预期的类型时,它会设置 failbit,并保持目标不变。

#include <iostream>
#include <sstream>

int main() {
    std::istringstream s("hello");
    int n = -1;
    if (!(s >> n)) std::cout << "could not read an int, n stays " << n << '\n';
    return 0;
}

清除状态

一旦设置了失败标志,流就会一直不可用,直到调用 clear() 将其重置。

#include <iostream>
#include <sstream>

int main() {
    std::istringstream s("x 42");
    int n;
    s >> n;          // fails on 'x'
    s.clear();       // reset state
    std::string word;
    s >> word;       // now reads 'x'
    std::cout << "recovered: " << word << '\n';
    return 0;
}

忽略错误输入

调用 clear() 后,使用 ignore() 丢弃有问题的字符,然后重试。

#include <iostream>
#include <sstream>
#include <limits>

int main() {
    std::istringstream s("bad 100");
    int n;
    while (!(s >> n)) {
        s.clear();
        s.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
    }
    std::cout << "read " << n << '\n';
    return 0;
}

区分 EOF 与错误

读取循环结束后,请检查它是正常的 eof(),还是实际的 bad() 失败。

#include <iostream>
#include <sstream>

int main() {
    std::istringstream s("1 2 3");
    int x;
    while (s >> x) {}
    std::cout << std::boolalpha << "reached eof: " << s.eof() << '\n';
    std::cout << "hardware error: " << s.bad() << '\n';
    return 0;
}

打开后检查

打开文件后务必立即验证流的状态,以便在路径缺失或无法读取时尽早失败。

#include <iostream>
#include <fstream>

int main() {
    std::ifstream in("absent_11111.txt");
    if (!in.is_open()) {
        std::cout << "open failed, aborting\n";
        return 1;
    }
    std::cout << "never reached\n";
    return 0;
}

启用异常

您可以要求流在发生错误时抛出异常,使用 exceptions() 将静默失败转换为可捕获的 std::ios_base::failure。

#include <iostream>
#include <fstream>

int main() {
    std::ifstream in;
    in.exceptions(std::ios::failbit);
    try {
        in.open("ghost_22222.txt");
    } catch (const std::exception& e) {
        std::cout << "caught open failure\n";
    }
    return 0;
}

验证读取数量

二进制 read 操作后,gcount() 会报告实际读取的字节数,从而帮助您检测读取不足。

#include <iostream>
#include <fstream>

int main() {
    int v = 9;
    std::ofstream("g.bin", std::ios::binary).write(reinterpret_cast<const char*>(&v), sizeof(v));
    int out;
    std::ifstream in("g.bin", std::ios::binary);
    in.read(reinterpret_cast<char*>(&out), sizeof(out));
    std::cout << "read " << in.gcount() << " bytes\n";
    return 0;
}

健壮的读取循环

将这些技巧结合起来:在循环中测试流,然后在循环结束后区分正常结束和错误。

#include <iostream>
#include <sstream>

int main() {
    std::istringstream s("5 10 15");
    int total = 0, x;
    while (s >> x) total += x;
    if (s.eof()) std::cout << "sum = " << total << " (clean)\n";
    else std::cout << "error during read\n";
    return 0;
}

快速检查

请检验您对流状态的理解。

回顾

您学到了流错误处理:

  • 状态标志为 good/eof/fail/bad,可以通过对应的方法查询,也可以将流作为 bool 进行测试
  • clear() 会重置状态,ignore() 会丢弃错误输入
  • 区分正常的 eof() 与实际错误;exceptions() 可以抛出异常,而 gcount() 可以验证二进制读取

下一课程:使用 <random> 生成随机数。

常见问题解答

「错误处理与状态」课时是免费的吗?

是的 — 「错误处理与状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C++ Academy 课程的其余内容,请升级到 CoddyKit PRO。 C++ Academy 课程共包含 4 节课。

「错误处理与状态」这节课中我会学到什么?

检查流状态 你通过在浏览器中直接运行的动手代码来练习 C++ Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C++ Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C++ Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「错误处理与状态」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C++ Academy 课中编写并运行代码吗?

能。每节 C++ Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 ifstream 读取文件
  2. 使用 ofstream 写入文件
  3. 二进制文件输入输出
  4. 错误处理与状态
← 返回 C++ Academy