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

CSV文件读取至二维数组后输出全零,求问题排查方案

C++读取CSV到二维数组输出全为零的问题排查

我编写了C++函数readFilesToReadings,试图将CSV文件中的数据读取到二维数组中,但打印数组时输出全为零,请问问题出在哪里?该文件包含5行500列数据。

用户提供的代码:

void readFilesToReadings() {
int row = 5;
int col = 10;

int myArray[row][col];
string fileName, BasefileName = "C:/Users/hhh/Desktop/frac/Z500.csv"
//Opening the file
ifstream inputfile(fileName);

if (!inputfile.is_open()) 
cout<<"Error opening file" ;

//Defining the loop for getting input from the file

for (int r = 0; r < row; r++) //Outer loop for rows
{
    for (int c = 0; c < col; c++) //inner loop for columns
    {
      inputfile >> myArray[r][c];  //Take input from file and put into myArray
    }
}

for (int r = 0; r < row; r++)
{
    for (int c = 0; c < col; c++)
    {
        cout << myArray[r][c] << "\t";
    }
    cout<<endl;
}

}

问题分析

直接点出代码中的核心问题:

  • 文件名未赋值:fileName变量未被赋予实际文件路径,始终是空字符串,导致文件无法打开。后续读取操作全部失败,数组未写入有效数据,输出的是局部数组未初始化的随机值(显示全零是巧合)。
  • CSV读取逻辑错误:>>运算符默认以空白字符(空格、换行)作为分隔符,但CSV文件用逗号分隔数据,直接用>>会把逗号当成数据的一部分,无法正确分割每一列的值。
  • 非标准变长数组:int myArray[row][col]属于C99的变长数组特性,并非C++标准语法,部分编译器仅作为扩展支持,移植性差。
  • 数组未初始化:局部数组未初始化,内存中是随机垃圾值,读取失败时输出的就是这些值。
  • 错误处理缺失:文件打开失败后未终止函数,后续仍执行无效的读取和打印操作。

修正后的代码示例

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

void readFilesToReadings() {
    const int row = 5;
    const int col = 500; // 匹配文件的500列
    std::string fileName = "C:/Users/hhh/Desktop/frac/Z500.csv";
    
    std::ifstream inputfile(fileName);
    if (!inputfile.is_open()) {
        std::cout << "Error opening file" << std::endl;
        return; // 打开失败直接返回,避免后续无效操作
    }

    // 使用vector替代变长数组,符合C++标准且自动初始化
    std::vector<std::vector<int>> myArray(row, std::vector<int>(col));
    std::string line;

    for (int r = 0; r < row; ++r) {
        if (!std::getline(inputfile, line)) {
            std::cout << "读取第" << r + 1 << "行失败" << std::endl;
            break;
        }
        std::stringstream ss(line);
        std::string token;
        int c = 0;
        // 按逗号分割每行数据
        while (std::getline(ss, token, ',') && c < col) {
            myArray[r][c++] = std::stoi(token);
        }
    }

    // 打印数组
    for (int r = 0; r < row; ++r) {
        for (int c = 0; c < col; ++c) {
            std::cout << myArray[r][c] << "\t";
        }
        std::cout << std::endl;
    }
}

修正说明

  1. 给fileName赋值正确的文件路径,确保文件能正常打开。
  2. 用std::vector<std::vector<int>>替代变长数组,符合C++标准,且默认初始化元素为零。
  3. 使用std::getline读取整行,结合std::stringstream按逗号分割数据,适配CSV格式。
  4. 完善错误处理,文件打开失败或行读取失败时及时终止操作并提示。
  5. 修正列数为500,匹配实际文件的列数。

更新1:这是针对用户20716902的回答所呈现的输出
enter image description here

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:01:05