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

C++ 如何读取分号分隔CSV文件,计算列总和及出现次数最多的值

实现方案

核心逻辑

  • 逐行读取CSV文件,第一行表头直接丢弃
  • 每一行按;分割得到3个字段,分别对应姓名、年龄、国家
  • 年龄字段转整型累加得到总和
  • 用哈希表统计每个国家的出现次数,遍历后得到出现频率最高的国家
  • 若需要将全量数据存入二维矩阵做后续处理,可以把每行分割后的结果存入vector<vector<string>>类型的容器中,通过下标访问任意位置的元素

完整代码

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
using namespace std;

// 按指定分隔符切割字符串,返回所有字段
vector<string> split(const string& s, char delimiter) {
    vector<string> tokens;
    string token;
    istringstream tokenStream(s);
    while (getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

int main() {
    fstream file("teste.csv");
    if (!file.is_open()) {
        cout << "文件打开失败" << endl;
        return 1;
    }

    string line;
    // 跳过表头行
    getline(file, line);

    int age_sum = 0;
    unordered_map<string, int> country_count;
    // 存储全量数据的二维矩阵,可选,不需要可以删除
    vector<vector<string>> all_data;

    while (getline(file, line)) {
        vector<string> fields = split(line, ';');
        // 存入二维矩阵
        all_data.push_back(fields);
        // 累加年龄
        age_sum += stoi(fields[1]);
        // 统计国家出现次数
        country_count[fields[2]]++;
    }

    // 找出现次数最多的国家
    string max_country;
    int max_count = 0;
    for (auto& pair : country_count) {
        if (pair.second > max_count) {
            max_count = pair.second;
            max_country = pair.first;
        }
    }

    // 输出结果
    cout << "年龄总和:" << age_sum << endl;
    cout << "出现次数最多的国家:" << max_country << endl;

    cin.get();
    return 0;
}

补充说明

如果需要后续操作其他行/列的数据,可以直接访问all_data[i][j],其中i是行索引(从0开始,对应数据的第一行),j是列索引(0对应name、1对应age、2对应country)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:36:03