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

C++从文件读取double类型数据到二维数组的代码问题排查

你的天气温度数据读取代码问题分析与修正

我仔细看了你的代码,能发现几个关键问题导致数据无法正确存入二维数组,咱们一个个拆解:

核心错误点

  • 文件指针未重置,且统计行数的逻辑有缺陷
    你第一次用while (!inFile.eof())循环统计行数后,文件指针已经移到了文件末尾,这时直接再次读取数据是读不到任何内容的。另外,用!inFile.eof()作为循环条件会导致最后一行被重复统计(因为eof标志是在尝试读取失败后才会触发的),正确的统计方式应该是在getline成功时才计数。

  • 数组索引完全错误
    不管是读取数据还是打印数据时,你都用了Temps[numRows][numCols]——但数组的索引是从0开始的,numRows和numCols是数组的总长度,用这个作为索引会直接访问越界的内存位置,这不仅存不了正确数据,还可能导致程序崩溃或出现奇怪的未定义行为。你应该用循环变量row和col来定位每个元素的位置。

  • 读取数据的循环逻辑缺失
    你当前的读取循环没有控制row和col的递增逻辑,就算文件指针没问题,也只会往同一个错误位置写入数据,根本没法填充整个二维数组。

修正后的完整代码

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

using namespace std;

int main() {
    ifstream inFile("weather_data.txt"); // 替换成你的实际文件名
    if (!inFile.is_open()) {
        cerr << "无法打开文件!" << endl;
        return 1;
    }

    int numCols = 12;
    int numRows = 0;
    string line;

    // 第一步:正确统计有效行数(跳过空行)
    while (getline(inFile, line)) {
        if (line.empty()) continue;
        numRows++;
    }

    // 重置文件指针到开头,清除之前的eof标志
    inFile.clear();
    inFile.seekg(0, ios::beg);

    // 动态分配二维数组
    double** Temps = new double*[numRows];
    for (int row = 0; row < numRows; row++) {
        Temps[row] = new double[numCols];
    }

    // 第二步:逐行读取数据到二维数组
    int currentRow = 0;
    while (getline(inFile, line) && currentRow < numRows) {
        istringstream iss(line);
        double temp;
        int currentCol = 0;
        while (iss >> temp && currentCol < numCols) {
            Temps[currentRow][currentCol] = temp;
            currentCol++;
        }
        currentRow++;
    }

    inFile.close();

    // 打印验证读取结果
    cout << "读取到的天气温度数据:" << endl;
    for (int row = 0; row < numRows; row++) {
        for (int col = 0; col < numCols; col++) {
            cout << Temps[row][col] << "\t";
        }
        cout << endl;
    }

    // 释放动态分配的内存,避免内存泄漏
    for (int row = 0; row < numRows; row++) {
        delete[] Temps[row];
    }
    delete[] Temps;

    return 0;
}

额外说明

  • 加入了文件打开失败的判断,避免程序在文件不存在时崩溃;
  • 用istringstream处理每行数据,确保能正确读取每行的12个double值;
  • 统计行数时跳过空行,避免无效行被误统计;
  • 最后添加了内存释放代码,修复了动态数组的内存泄漏问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:17:44