仅当某些值在 c++ 中保持不变时才读取某些列
Reading certain column only if certain value remain the same in c++
我正在尝试从包含某些列的数据文件创建对象,仅当质量(即第一列)保持不变时。这是我目前的尝试——
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)
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 一种在C++中读取TXT配置文件的简单方法