英文:
while loop used to read a .dat file c++
问题
我正在尝试读取一个包含11个数字的.dat文件,代码会检测它们之间的时间增量(这是在.dat文件中设置的任意值)。我正在使用while循环来处理文件中的其他数字,但当我使用它时,屏幕上只显示文件的第一个值,然后是零。
我的代码如下:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
double npts;
double time_inc;
double seismicData;
ifstream myFile;
ifstream fin;
int main()
{
ifstream fin("SEISMIC.dat", ios::in);
myFile.open("SEISMIC.dat");
fin >> npts;
cout << "数据点数: " << npts;
fin >> time_inc;
cout << " 时间增量:" << time_inc;
int num;
if (!myFile) {
cout << "错误:文件无法打开" << endl;
exit(1);
}
myFile >> num;
fin >> num;
while (!myFile.eof()) {
cout << "下一个数字是:" << num << endl;
myFile >> num;
}
myFile.close();
}
我想知道是否有人可以帮助我。附上了.dat文件的截图。
英文:
I am trying to read a .dat file of 11 numbers, the code detects the time incrementation between them(this is an arbitrary value set in the .dat file). I am using while loop to process the other numbers in the fil, but when I use it, only the first value of the file appears on the graphics screen followed by zeros.
my code is as follows:
#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();
}
I'm wondering if anyone could help me out. Attached is a screenshot of the .dat file
答案1
得分: 1
以下是翻译好的部分:
这里有一些用于从文本文件中读取所有数字并将它们回显到标准输出的代码。
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("SEISMIC.dat");
if (!file.is_open())
std::cerr << "无法打开文件\n";
int num;
while (file >> num)
std::cout << num << '\n';
}
如您所见,不需要太多的代码。然而,如果文件不符合您描述的格式,此代码将无法工作。
希望这对您有所帮助。
英文:
Here's some code to read all the numbers from a text file and echo them to the standard output.
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("SEISMIC.dat");
if (!file.is_open())
std::cerr << "cannot open file\n";
int num;
while (file >> num)
std::cout << num << '\n';
}
As you can see, not much code is needed. However this code will not work if the file is not in the format you described.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论