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

C++如何根据文件内整数数量动态调整数组的SIZE值

核心问题说明
  • C++中被const修饰的变量初始化后无法修改,同时栈内存上的固定长度数组要求长度必须是编译期可确定的常量,你运行时统计得到的整数个数是运行时变量,无法用来修改SIZE、也无法直接定义栈数组。
  • 统计整数个数的while循环已经将文件流的读指针移动到了文件末尾,同时触发了流的EOF错误标记,直接调用readData无法读取到任何数据。
解决实现方案

推荐优先使用C++ STL提供的vector动态数组容器,无需手动管理内存,天然支持运行时动态调整长度,修改后的代码如下:

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

// 传入动态数组的引用和文件流
void readData(istream& inFile, vector<int>& intArray) {
    for (int i = 0; i < intArray.size(); i++){
        inFile >> intArray[i];
        cout << intArray[i] << " ";
    }
}

int main() {
    ifstream inFile;
    string inFileName = "intValues.txt";
    inFile.open(inFileName.c_str());
    if (!inFile.is_open()) { // 可选:增加文件打开失败判断,提升鲁棒性
        cout << "文件打开失败" << endl;
        return 1;
    }
    
    int value, count = 0;
    while(inFile >> value){
        count += 1;
    }
    cout << "整数个数:" << count << endl;

    // 重置文件流状态和读指针
    inFile.clear(); // 清除EOF等错误标记
    inFile.seekg(0, ios::beg); // 将读指针移动到文件开头

    // 定义长度为count的动态数组
    vector<int> intArray(count);
    readData(inFile, intArray);

    // vector内存会自动回收,无需手动释放
    return 0;
}

如果你必须使用原生数组实现,可以用堆内存动态分配的方式,修改对应部分即可:

// 统计完count,重置文件流后
int* intArray = new int[count]; // 动态分配堆内存数组
// 调用readData读取数据...
// 程序结束前手动释放内存避免泄漏
delete[] intArray;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:15:03