跳到内容

简单文件输出与字符处理 ​

到目前为止所有输入输出都走 cin/cout——关掉终端数据就没了。把结果写进文件、再从文件读回来,是很多实用程序的基本能力。这一节介绍简单的文件 I/O,以及 <cctype> 提供的字符分类与转换函数。

写文件:std::ofstream ​

<fstream> 头文件提供文件流类。写文件用 std::ofstream(output file stream):

cpp
// outfile.cpp
#include <iostream>
#include <fstream>     // 文件流
#include <string>

int main()
{
    std::string item = "笔记本";
    int qty = 12;
    double price = 4.5;

    std::ofstream outFile;             // 创建输出文件流对象
    outFile.open("inventory.txt");     // 关联到一个文件

    if (!outFile.is_open())
    {
        std::cout << "打开文件失败\n";
        return 1;
    }

    // 用法和 cout 完全一样,只是流向文件
    outFile << "商品名:" << item << "\n";
    outFile << "数量:" << qty << "\n";
    outFile << "单价:" << price << "\n";
    outFile << "总价:" << qty * price << "\n";

    outFile.close();                   // 用完关闭
    std::cout << "已写入 inventory.txt\n";
    return 0;
}

ofstream 的用法和 cout 几乎一样——都是输出流,<< 都能用。区别只是 cout 流向屏幕,ofstream 流向文件。open() 把流对象和一个文件名关联,close() 关闭。养成"用完就 close()"的习惯。

is_open() 检查是否成功打开——目录不存在、无权限等情况会失败,检查一下能避免后续写入丢失。

读文件:std::ifstream ​

读文件用 std::ifstream(input file stream),用法类似 cin:

cpp
// sumafile.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>      // exit、EXIT_FAILURE

int main()
{
    std::ifstream inFile;
    inFile.open("inventory.txt");

    if (!inFile.is_open())
    {
        std::cout << "打开文件失败\n";
        std::exit(EXIT_FAILURE);       // 直接退出程序
    }

    // 读法 1:逐个值读取
    double value;
    double sum = 0.0;
    int count = 0;

    while (inFile >> value)            // 读成功返回真
    {
        ++count;
        sum += value;
    }

    if (count > 0)
        std::cout << "读入 " << count << " 个数,总和 " << sum
                  << ",平均 " << sum / count << "\n";
    else
        std::cout << "没有读到数字\n";

    inFile.close();
    return 0;
}

inFile >> value 和 cin >> value 行为一致——按类型读取、跳过空白。读到文件尾时返回假,循环结束。

读完后可以区分结束原因:inFile.eof() 为真表示正常到尾,inFile.fail() 为真但 eof() 为假表示格式不符(比如期望数字却读到文字)。

文件流与控制流的统一 ​

ofstream 和 cout 都是输出流,ifstream 和 cin 都是输入流。这意味着你可以把同一个函数同时用于屏幕和文件,只要传"流"进去。这种统一是 C++ 流库的核心设计:

cpp
#include <iostream>
#include <fstream>

// 给任意输出流写一行报告
void writeReport(std::ostream& os)
{
    os << "------ 报告 ------\n";
    os << "状态:正常\n";
}

int main()
{
    writeReport(std::cout);                 // 打到屏幕
    std::ofstream f("report.txt");
    writeReport(f);                         // 打到文件
    f.close();
    return 0;
}

参数类型是 std::ostream&(输出流的基类引用),cout 和 ofstream 都能传进去。这种"以流为参数"的写法后续章节会更深入。

<cctype> 字符处理 ​

标准库 <cctype> 提供一组字符分类和转换函数,比手写范围判断更清晰、还能正确处理本地字符集:

函数判断
isalpha(c)是否字母
isdigit(c)是否数字
isalnum(c)是否字母或数字
isspace(c)是否空白(空格、制表、换行等)
ispunct(c)是否标点
isupper(c) / islower(c)是否大写/小写
toupper(c)转大写(返回转换后的值,不改实参)
tolower(c)转小写
cpp
// cctypes.cpp
#include <iostream>
#include <cctype>

int main()
{
    char ch;
    int letters = 0, digits = 0, spaces = 0, puncts = 0, others = 0;

    std::cout << "输入文字,以 @ 结束:\n";
    std::cin.get(ch);
    while (ch != '@')
    {
        if (std::isalpha(ch))       ++letters;
        else if (std::isdigit(ch))  ++digits;
        else if (std::isspace(ch))  ++spaces;
        else if (std::ispunct(ch))  ++puncts;
        else                        ++others;
        std::cin.get(ch);
    }

    std::cout << "字母 " << letters << ",数字 " << digits
              << ",空白 " << spaces << ",标点 " << puncts
              << ",其他 " << others << "\n";
    return 0;
}

对比上一章手写 ch >= 'a' && ch <= 'z' 的写法,isalpha 更简洁,也更可移植。处理字符分类时优先用 <cctype>。

大小写转换 ​

toupper / tolower 返回转换后的值,不改原来的字符,要赋值回去才生效:

cpp
#include <iostream>
#include <cctype>
#include <string>

int main()
{
    std::string word = "Hello";
    for (char& c : word)          // 用引用才能改原字符
        c = static_cast<char>(std::toupper(c));
    std::cout << word << "\n";    // HELLO
    return 0;
}

注意 toupper 返回 int,赋回 char 时用 static_cast 显式转换更安全,避免窄化警告。

课后练习 ​

  1. 写文件:写一个程序,让用户输入姓名和年龄,用 std::ofstream 把它们写进 info.txt,每行一项。提示:open 后用 << 写入,和 cout 用法一致,最后 close。
  2. 读文件求和:写一个文本文件,每行一个数字,然后用 std::ifstream 配合 while (in >> value) 读入所有数字,打印个数、总和、平均值。提示:检查 is_open(),读完后用 eof() 确认是正常到尾。
  3. 字符统计:用 <cctype> 的 isalpha、isdigit、isspace、ispunct 改写一段逐字符分类的程序(读入到 @ 结束),统计每类字符个数。提示:比手写 'a' <= ch && ch <= 'z' 更清晰。
  4. 大小写转换:读入一个单词,用 toupper 把它全部转成大写打印,再用 tolower 全部转小写打印。提示:toupper 返回的是新值,不改原字符,要赋值回去;范围 for 循环里用 char& 引用才能修改原字符串。