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

C++循环读取payroll.dat无法获取连续数据及核心转储问题求助

问题分析与修复方案

核心问题梳理

你的代码存在几个关键错误,导致读取异常和核心转储:

  1. 未初始化变量引发越界访问

    • finder变量声明后未赋值,初始值是随机垃圾值,第一次访问Array[finder]就会越界,直接触发核心转储。
    • loop用double类型做循环计数不合适,浮点类型可能出现精度误差,应该用int。
  2. 数据类型不匹配

    • 文件里是带小数的double数值,但你用int copy1读取、int Array[]存储,会截断小数部分,还可能导致读取逻辑异常。
  3. 逻辑顺序错误

    • 每次循环都创建7个Payroll对象,但此时数组数据还没读取完全,后面的元素都是未初始化的垃圾值,输出毫无意义。
  4. 未检查文件状态

    • 打开文件后没判断是否成功,若文件不存在/路径错误,程序会继续执行,导致读取失败。

修正后的代码

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

// 改为double数组,匹配文件数值类型
double Array[14];

class Payroll {
public:
    double hourlyrate;
    double hours;

    // 用初始化列表初始化成员,更规范
    Payroll(double Hourlyrate, double Hours) : hourlyrate(Hourlyrate), hours(Hours) {}
};

int main() { 
    double copy1; // 改为double类型,保留小数
    int finder = 0; // 初始化索引,从数组第0位开始
    int loop = 0; // 用int计数,循环14次对应14个数值

    ifstream info;
    info.open("payroll.dat");

    // 必须检查文件是否成功打开
    if (!info.is_open()) {
        cout << "无法打开payroll.dat文件" << endl;
        return 1;
    }

    // 先完整读取所有数据到数组
    while (loop < 14) {
        info >> copy1;
        Array[finder] = copy1; // 直接赋值,原代码的累加是错误的(数组初始为垃圾值)
        
        // 临时输出验证读取情况
        cout << "已读取第" << loop+1 << "个值:" << copy1 << endl;

        loop++;
        finder++;
    }

    // 数据读取完成后,再创建员工对象
    Payroll Emp1(Array[0], Array[1]);
    Payroll Emp2(Array[2], Array[3]);
    Payroll Emp3(Array[4], Array[5]);
    Payroll Emp4(Array[6], Array[7]);
    Payroll Emp5(Array[8], Array[9]);
    Payroll Emp6(Array[10], Array[11]);
    Payroll Emp7(Array[12], Array[13]);

    // 输出员工数据验证
    cout << "\n员工信息:" << endl;
    cout << "员工1:时薪" << Emp1.hourlyrate << ",工时" << Emp1.hours << endl;
    cout << "员工2:时薪" << Emp2.hourlyrate << ",工时" << Emp2.hours << endl;
    cout << "员工3:时薪" << Emp3.hourlyrate << ",工时" << Emp3.hours << endl;
    cout << "员工4:时薪" << Emp4.hourlyrate << ",工时" << Emp4.hours << endl;
    cout << "员工5:时薪" << Emp5.hourlyrate << ",工时" << Emp5.hours << endl;
    cout << "员工6:时薪" << Emp6.hourlyrate << ",工时" << Emp6.hours << endl;
    cout << "员工7:时薪" << Emp7.hourlyrate << ",工时" << Emp7.hours << endl;

    info.close(); // 关闭文件
    return 0;
}

关键修正说明

  • 初始化所有变量,彻底避免数组越界和随机值问题。
  • 统一使用double类型存储数值,保留文件中的小数精度。
  • 调整逻辑顺序:先读完全部数据,再创建对象,确保对象使用有效数据。
  • 添加文件打开状态检查,提前处理文件不存在的异常情况。
  • 移除原代码中错误的累加逻辑,直接赋值即可正确存储读取的数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:20:24