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

C++如何从文件读取数字存入数组?代码输出异常大值求解

问题描述

程序预期实现功能:生成30个随机数写入文件,再将文件内存储的数字读取并存入数组。实际运行打印数组内容时,输出结果并非文件中存储的正确数值,而是无意义的超大随机数。
原实现代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;

void sortFile() {
    
    fstream f;
    int numbers[30];
    int n;
    
    f.open("f.txt");
    
    
    
    srand(time(NULL));
    for(int i; i < 30; i++) {
        f << rand() % 30 + (-9) << endl;
        
    }
    
    while(!f.eof()) {
        
        f >> numbers[n];
        n++;
    }
        
    f.close();
    
    for(int i; i<30;i++) {
        cout << numbers[i] << endl;
    }
        

}


int main() {
    
    sortFile();
    
}
错误原因
  • 所有局部循环变量i、读取下标变量n均未初始化,C++中局部栈变量未初始化时存储的是内存残留的随机垃圾值,会直接导致循环执行次数错乱、数组下标越界,是输出无意义超大数值的核心原因。
  • 文件打开时未指定读写模式,写入完成后文件指针停留在文件末尾,没有重置指针位置就直接读取,根本无法读到之前写入的内容。
  • 使用while(!f.eof())作为读取判断条件存在逻辑缺陷,会在文件末尾多读一次无效值,造成数组越界。
  • 写入操作完成后没有重置流状态,直接切换到读模式会触发流错误,导致读取操作完全失效。
修复方案

修复所有问题后的可运行代码如下:

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;

void sortFile() {
    fstream f;
    int numbers[30];
    int n = 0; // 初始化读取下标
    
    // 指定打开模式为可读可写,打开时清空原有文件内容避免干扰
    f.open("f.txt", ios::out | ios::in | ios::trunc);
    srand(time(NULL));
    
    // 初始化循环变量i为0
    for(int i = 0; i < 30; i++) {
        f << rand() % 30 + (-9) << endl;
    }
    
    f.clear(); // 重置流错误状态
    f.seekg(0, ios::beg); // 将文件读指针移动到文件开头
    
    // 读取时直接判断流读取是否成功,同时限制读取数量不超过数组长度,避免越界
    while(n < 30 && f >> numbers[n]) {
        n++;
    }
        
    f.close();
    
    // 初始化循环变量i为0
    for(int i = 0; i<30;i++) {
        cout << numbers[i] << endl;
    }
}

int main() {
    sortFile();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:03:22