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

Python开发者求C++实现读取TXT并提取键值存入STL map方案

C++解析特定格式TXT并存储到STL Map实现方案

问题背景

你需要读取格式为Title="XXX" Description="XXX"的TXT文件,逐行解析Title和Description值并存入STL map,目前卡在字符串分割环节。以下是完整实现逻辑和优化方案。

示例文件内容

Title="Hello World" Description="First test line"
Title="C++ String Parse" Description="Handling quoted values"
Title="File IO" Description="Optimize text reading"

参考Python实现

import re
from collections import defaultdict

data_map = {}
# 正则匹配捕获引号内的内容
pattern = re.compile(r'Title="(.*?)" Description="(.*?)"')

with open('data.txt', 'r') as f:
    for line in f:
        match = pattern.match(line.strip())
        if match:
            title = match.group(1)
            desc = match.group(2)
            data_map[title] = desc

C++完整实现

方式1:手动字符串解析(高效适配固定格式)

手动查找字符串位置,避免正则开销,适合格式固定的场景:

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>

using namespace std;

// 解析单行,提取Title和Description,成功返回true
bool parseLine(const string& line, string& title, string& desc) {
    // 定位Title起始和结束引号
    size_t title_start = line.find("Title=\"");
    if (title_start == string::npos) return false;
    title_start += 7; // 跳过"Title=\""长度
    size_t title_end = line.find("\"", title_start);
    if (title_end == string::npos) return false;
    title = line.substr(title_start, title_end - title_start);

    // 定位Description起始和结束引号
    size_t desc_start = line.find("Description=\"", title_end);
    if (desc_start == string::npos) return false;
    desc_start += 13; // 跳过"Description=\""长度
    size_t desc_end = line.find("\"", desc_start);
    if (desc_end == string::npos) return false;
    desc = line.substr(desc_start, desc_end - desc_start);

    return true;
}

int main() {
    map<string, string> data_map;
    ifstream input_file("data.txt");
    
    if (!input_file.is_open()) {
        cerr << "Error: Failed to open file!" << endl;
        return 1;
    }

    string line;
    // 逐行读取解析
    while (getline(input_file, line)) {
        if (line.empty()) continue; // 跳过空行
        string title, desc;
        if (parseLine(line, title, desc)) {
            data_map[title] = desc;
        } else {
            cerr << "Warning: Invalid line format - " << line << endl;
        }
    }

    input_file.close();

    // 验证结果
    for (const auto& entry : data_map) {
        cout << "Title: " << entry.first << " | Description: " << entry.second << endl;
    }

    return 0;
}

方式2:正则表达式解析(通用适配格式变化)

如果格式可能有调整(比如空格数量变化),用正则更灵活,需要C++11及以上版本:

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <regex>

using namespace std;

int main() {
    map<string, string> data_map;
    // 正则表达式:捕获引号内的Title和Description内容
    regex line_pattern(R"(Title="(.*?)"\s+Description="(.*?)")");
    ifstream input_file("data.txt");

    if (!input_file.is_open()) {
        cerr << "Error: Failed to open file!" << endl;
        return 1;
    }

    string line;
    while (getline(input_file, line)) {
        if (line.empty()) continue;
        smatch match_results;
        if (regex_search(line, match_results, line_pattern)) {
            // match_results[0]是整个匹配串,1是Title,2是Description
            if (match_results.size() == 3) {
                string title = match_results[1].str();
                string desc = match_results[2].str();
                data_map[title] = desc;
            }
        } else {
            cerr << "Warning: Invalid line format - " << line << endl;
        }
    }

    input_file.close();

    // 验证结果
    for (const auto& entry : data_map) {
        cout << "Title: " << entry.first << " | Description: " << entry.second << endl;
    }

    return 0;
}

更优文件读取方案

  1. 标准逐行读取(常规场景首选)
    使用std::getline配合std::ifstream是C++处理文本文件的标准方式,自动兼容Windows/Unix换行符,代码简洁易维护。

  2. 批量读取(大文件优化)
    针对超大型文本文件,一次性读取整个文件到内存再分割处理,减少IO操作次数:

    #include <sstream>
    
    // 一次性读取文件内容到字符串
    string readFileToMemory(const string& filename) {
        ifstream file(filename);
        if (!file) {
            cerr << "Error: Failed to open file!" << endl;
            return "";
        }
        stringstream buffer;
        buffer << file.rdbuf(); // 读取全部内容到buffer
        return buffer.str();
    }
    
    // 调用示例
    int main() {
        map<string, string> data_map;
        string file_content = readFileToMemory("data.txt");
        stringstream content_stream(file_content);
        string line;
        while (getline(content_stream, line)) {
            // 解析每行逻辑同前...
        }
        return 0;
    }
    
  3. 容器选择优化
    如果不需要按键排序,用std::unordered_map替代std::map,插入和查找的平均时间复杂度为O(1),性能更优。

  4. 错误处理增强
    可以添加文件权限检查、行格式错误的详细日志,方便定位问题。

内容的提问来源于stack exchange,提问作者Nipun Kumar Goel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:39:20