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

如何用C++从含两列多行整数的CSV文件生成整数二维数组

在C++中从两列整数CSV生成整数二维数组

嘿,我太懂你那种找到的方案全是字符串处理的烦躁了——明明数据都是整数,为啥还要绕一大圈转字符串?直接操作整数才是最顺的路子!针对你这个两列多行的整数CSV文件,我给你整个简洁直接的实现,完全不用多余的字符串转换步骤:

推荐方案:用vector构建动态二维数组(安全省心)

C++里的vector天生适合这种行数不确定的场景,不用手动管理内存,还能自动扩展。直接看代码:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() {
    // 定义二维整数数组(用vector更灵活)
    vector<vector<int>> intArray;
    ifstream csvFile("your_file.csv"); // 替换成你的CSV文件名

    if (!csvFile.is_open()) {
        cerr << "Failed to open the CSV file!" << endl;
        return 1;
    }

    int num1, num2;
    char comma; // 用来跳过两列之间的逗号

    // 循环读取每一行的两个整数
    while (csvFile >> num1 >> comma >> num2) {
        // 把当前行的两个整数存入一个一维vector
        vector<int> row = {num1, num2};
        // 将这一行加入二维数组
        intArray.push_back(row);
    }

    csvFile.close();

    // 测试输出一下结果,验证是否正确
    cout << "生成的二维数组内容:" << endl;
    for (const auto& row : intArray) {
        cout << row[0] << ", " << row[1] << endl;
    }

    return 0;
}

关键细节说明:

  • 读取逻辑:csvFile >> num1 >> comma >> num2会自动跳过换行符和空格,同时精准读取两个整数之间的逗号,完美适配你的两列CSV格式
  • vector<vector<int>>会自动根据CSV的行数动态扩展,不用提前知道总共有多少行
  • 全程直接操作整数,不用任何字符串处理函数,效率更高也更直观

备选:用原生动态二维数组(适合必须用指针的场景)

如果你一定要用原生的int**类型数组,也可以这么做,只是要注意手动释放内存避免泄漏:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() {
    ifstream csvFile("your_file.csv");
    if (!csvFile.is_open()) {
        cerr << "Failed to open the file!" << endl;
        return 1;
    }

    // 先统计总行数(需要先遍历一遍文件)
    int numRows = 0;
    int num1, num2;
    char comma;
    while (csvFile >> num1 >> comma >> num2) {
        numRows++;
    }
    // 重置文件指针到开头
    csvFile.clear();
    csvFile.seekg(0);

    // 分配二维数组内存
    int** intArray = new int*[numRows];
    for (int i = 0; i < numRows; i++) {
        intArray[i] = new int[2]; // 固定两列
    }

    // 重新读取数据存入数组
    for (int i = 0; i < numRows; i++) {
        csvFile >> intArray[i][0] >> comma >> intArray[i][1];
    }

    csvFile.close();

    // 测试输出
    cout << "生成的二维数组内容:" << endl;
    for (int i = 0; i < numRows; i++) {
        cout << intArray[i][0] << ", " << intArray[i][1] << endl;
    }

    // 记得释放内存!
    for (int i = 0; i < numRows; i++) {
        delete[] intArray[i];
    }
    delete[] intArray;

    return 0;
}

注意事项:

这个方案需要先遍历文件统计行数,然后才能分配对应大小的内存,用完之后必须手动释放每一行的内存再释放外层指针,不然会造成内存泄漏。所以还是更推荐用vector的方案,省心又安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:17:59