仅当某些值在 c++ 中保持不变时才读取某些列

Reading certain column only if certain value remain the same in c++

本文关键字:读取 c++      更新时间:2023-10-16

我正在尝试从包含某些列的数据文件创建对象,仅当质量(即第一列)保持不变时。这是我目前的尝试——

void read_mass() {
        vector<double> value(29);
        double _value ;
        double _mass ;
        double _next_mass ;
        _file >> _mass ;
        WimpData* mDM = new WimpData(_mass) ;
        _next_mass = _mass ;
        cout << "Reading data for mass " << _mass << endl;
        do {
            for (int i=0 ; i < 29 ; i++) {
                _file >> _value ;
                value[i]=_value;
                cout << value[i] << " ";
            }
            mDM->add_line(value[0] ,value[23],value[24],value[25]);
            if (_file.eof()) break ;
            _file >> _next_mass ;
        } while (_next_mass == _mass) ;
        _wimp.insert(pair<double, WimpData*>(_mass, mDM));
        cout << "Finished reading data for mass " << _mass << endl ;
    }

我第一次使用此功能时,它正常工作。在第二次调用中,我看到文件的指针没有停留在质量具有新值的位置,而只是步进了一步。

我怎样才能使文件的指针在 do-while 循环中继续计数?

问题是因为你读取了_next_mass,在下一次执行中,你从读取第一个值开始_mass(你之前在执行中读过它)。

例如,您可以做类来读取它,并将上次读取的质量保存在私有变量中。 并添加任何函数 init() 来读取初始质量。

快速解决方案:

double _mass = -1.0; //initial mass firstly not read (-1)
void read_mass() {
    vector<double> value(29);
    double _value ;
    double _next_mass ;
    if(_mass == -1)
        _file >> _mass ;
    WimpData* mDM = new WimpData(_mass) ;
    _next_mass = _mass ;
    cout << "Reading data for mass " << _mass << endl;
    do {
        for (int i=0 ; i < 29 ; i++) {
            _file >> _value ;
            value[i]=_value;
            cout << value[i] << " ";
        }
        mDM->add_line(value[0] ,value[23],value[24],value[25]);
        if (_file.eof()) break ;
        _file >> _next_mass ;
    } while (_next_mass == _mass) ;
    _wimp.insert(pair<double, WimpData*>(_mass, mDM));
    cout << "Finished reading data for mass " << _mass << endl ;

    _mass = _next_mass; //we readed the first mass of next line (save it)
}