You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++在文本文件的每个逗号后添加空格?

如何用C++在CSV文件的每个逗号后添加空格?

你的目标文件内容如下:

100,Nguyen Van A,2004
101,Tran Thi B,2004
102,Vo Van C,2005
103,Truong Thi D,2005

你之前尝试的代码存在两个关键问题:

  1. 用getline(svFile, line, ',')读取时,分隔符是逗号,所以每次读取的line里不会包含逗号,line.find(",")永远返回npos,自然不会执行添加空格的逻辑。
  2. 直接对打开的输入文件流执行写操作是错误的,不能同时读写同一个打开的文件流,会导致数据混乱或操作失败。

下面是两种可行的解决方案:

方案一:一次性读取整个文件内容后替换

这种方式适合文件体积不大的场景,操作简单:

#include <fstream>
#include <string>

int main() {
    // 读取文件全部内容到字符串
    std::ifstream inFile("list_student.txt");
    std::string content((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
    inFile.close();

    // 遍历替换所有逗号为", "
    size_t pos = 0;
    while ((pos = content.find(',', pos)) != std::string::npos) {
        content.replace(pos, 1, ", ");
        pos += 2; // 跳过已替换的", ",避免重复处理
    }

    // 将处理后的内容写回原文件(也可以写入新文件)
    std::ofstream outFile("list_student.txt");
    outFile << content;
    outFile.close();

    return 0;
}

方案二:逐行读取并处理

如果文件体积较大,逐行处理更节省内存:

#include <fstream>
#include <string>

int main() {
    std::ifstream inFile("list_student.txt");
    std::ofstream outFile("list_student_processed.txt"); // 写入新文件,避免覆盖原文件出错
    std::string line;

    while (std::getline(inFile, line)) {
        size_t pos = 0;
        while ((pos = line.find(',', pos)) != std::string::npos) {
            line.replace(pos, 1, ", ");
            pos += 2;
        }
        outFile << line << '\n';
    }

    inFile.close();
    outFile.close();

    return 0;
}

注意事项

  • 若要覆盖原文件,优先用方案一的“先读入内存再写入”方式,避免读写冲突;如果用方案二,处理完后可以用文件操作(比如std::filesystem::rename)把新文件替换成原文件。
  • 替换时pos += 2是因为替换后的内容占2个字符(, ),从下一个位置继续查找能避免重复处理同一位置。

内容的提问来源于stack exchange,提问作者Duyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:10:12