我正在开发一个小程序,以帮助加快我的实验室工作的一些数据分析速度。它应该从文本文件中读取数据,创建一堆包含这些数据的数组,然后进行一些数学运算。
我一直遇到的问题是我不知道原始文本文件有多少行,所以我不知道要制作多大的数组。我对 C++ 很陌生,现在我对动态大小的数组感到不舒服,这里有一些代码
// first determine the length of the file
ifstream dataFile ("xys_data.txt");
const int LENGTH = count(istreambuf_iterator<char>(dataFile), istreambuf_iterator<char>(), '\n'); // counts the number of new lines
// declare vector of type datapoint
dataPoint data[LENGTH];
当我尝试编译这个时,我收到错误
expected constant expression
cannot allocate an array of constant size 0
'data' : unknown size
但我不是把 LENGTH 定义为常数吗?
任何帮助将不胜感激。
EDIT
按照几乎所有人的建议,我开始使用 std::vector。我还有最后一个问题,我对此有点犹豫不决。
在第一次尝试该程序时,我定义了一个数据结构:
struct dataPoint
{
double x; // x values
double y; // y values
double s; // sigma values
};
然后,当我从文件中读取数据时,我将其发送到这个结构,如下所示
while (!dataFile.eof()) // this loop writes out each row of data to the arrays x, y, s until it reaches the end of the file
{
int j = 0;
dataFile >> data[j].x >> data[j].y >> data[j].s;
j++;
}
有没有办法使用向量来做到这一点?我的第一个想法是定义向量 x、y 和 s 并替换data[j].x
with x
在循环中,但这不起作用。