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

C++如何读取文本文件特殊字符区间及指定符号后数据并存储为double类型

实现思路

  1. 状态标记:设置两个布尔标记,分别标识当前是否处于##与**的读取区间、是否已经到达%%之后的读取区间,初始值均为false。
  2. 逐行判断:打开文件后逐行读取内容,先判断当前行是否为标记行,对应修改状态值,标记行本身不需要处理内容。
  3. 特殊字符过滤:对需要处理的有效行,遍历内容把所有<和>替换为空格,利用C++输入流自动跳过空白的特性,后续可以直接按顺序读取数值。
  4. 数值存储:用字符串输入流从处理后的行中读取三个double类型数值,存入自定义容器即可。

完整实现代码

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <tuple>

// 替换字符串中的<和>为空格
void replace_special_char(std::string& s) {
    for (char& c : s) {
        if (c == '<' || c == '>') {
            c = ' ';
        }
    }
}

int main() {
    // 替换为你的实际文件路径
    std::ifstream in_file("data.txt");
    if (!in_file.is_open()) {
        std::cout << "文件打开失败" << std::endl;
        return 1;
    }

    bool read_between_hash_asterisk = false;
    bool read_after_percent = false;
    // 存储结果,每个元素对应一行的三个double数值,也可以替换为自定义结构体
    std::vector<std::tuple<double, double, double>> result;

    std::string line;
    while (std::getline(in_file, line)) {
        // 判断标记行,修改读取状态
        if (line.find("##") != std::string::npos) {
            read_between_hash_asterisk = true;
            continue;
        }
        if (line.find("**") != std::string::npos) {
            read_between_hash_asterisk = false;
            continue;
        }
        if (line.find("%%") != std::string::npos) {
            read_after_percent = true;
            continue;
        }

        // 不在有效读取区间则跳过当前行
        if (!read_between_hash_asterisk && !read_after_percent) {
            continue;
        }

        // 处理特殊字符后读取数值
        replace_special_char(line);
        std::istringstream iss(line);
        double v1, v2, v3;
        if (iss >> v1 >> v2 >> v3) {
            result.emplace_back(v1, v2, v3);
        }
    }

    in_file.close();

    // 验证输出,可根据需求删除
    for (const auto& item : result) {
        std::cout << std::get<0>(item) << " " << std::get<1>(item) << " " << std::get<2>(item) << std::endl;
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者gangwarady

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:09:03