C++使用while循环读取.dat文件异常:仅显示首个值其余为0
问题描述
我尝试读取一个包含11个数值的SEISMIC.dat文件,代码需要检测数值间的时间增量(文件中设定的任意值)。但使用while循环处理文件其余数值时,仅文件首个值显示在屏幕上,后续均为0。
原代码如下:
#include <fstream> #include <iostream> #include <string> using namespace std; //int k; double npts; double time_inc; //double sensor; double seismicData; //double new_double; ifstream myFile; ifstream fin; //ifstream dataOutput;` int main() { //this takes the data and analyses the number of points as well as the time incr. ifstream fin("SEISMIC.dat", ios::in); myFile.open("SEISMIC.dat"); fin >> npts; cout << "Number of data points: " << npts; fin >> time_inc; cout << " Time incrementation:" << time_inc; int num; //myFile.open("SEISMIC.dat"); if (!myFile) { cout << "Error: file could not be opened" << endl; exit(1); } myFile >> num; fin >> num; //myFile >> seismicData; while (!myFile.eof()) { cout << "Next number is:" << num <<endl; myFile >> num; //cout << "Next number is:" << fin << endl; //cout << seismicData << endl; //myFile >> seismicData; } myFile.close(); }
问题原因与修复
你的代码存在三个核心问题:
- 同时用两个
ifstream(fin和myFile)读取同一文件,导致读取指针混乱,完全没必要。 - 用
!myFile.eof()作为循环条件是错误的,会导致读取失败后仍执行输出,且读取顺序逻辑错误。 - 存储数据的
num是int类型,但文件中是浮点数值,类型不匹配引发读取失败,后续值变为0。
修正后的代码:
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { double npts; double time_inc; double seismicData; ifstream myFile("SEISMIC.dat"); if (!myFile) { cout << "Error: file could not be opened" << endl; exit(1); } // 读取点数和时间增量 myFile >> npts >> time_inc; cout << "Number of data points: " << npts << endl; cout << " Time incrementation: " << time_inc << endl; // 循环读取剩余数据,用读取操作本身作为条件判断是否成功 while (myFile >> seismicData) { cout << "Next number is: " << seismicData << endl; } myFile.close(); return 0; }
关键修复点
- 仅使用一个
ifstream对象操作文件,避免读取位置冲突。 - 改用
myFile >> seismicData作为循环条件,既完成读取,又能准确判断是否读取到有效数据,规避eof()的陷阱。 - 将数据存储变量改为
double类型,匹配文件中的数值类型,防止读取失败。 - 移除全局变量,将变量放在局部作用域,代码更安全整洁。
内容的提问来源于stack exchange,提问作者Luke Adams
相关产品推荐
相关产品推荐

