将文件中的逐行数据提取到C++中的动态数组中

Extracting line by line data from file into dynamic array in C++

本文关键字:C++ 动态 数组 数据 文件 逐行 提取      更新时间:2023-10-16

我正在尝试从文件中提取数据并将其放入数据类型为DataBlock(DataBlock是结构)的动态数组中。问题是数据在 for 循环的第一次迭代中被正确提取,但在之后没有。我已经调试过了,问题是指针在第一次迭代 for 循环并将第一次迭代的最后一个值分配给整个数组后没有移动到下一行。

编辑:现在我意识到问题是由于文件中的" ****",因为这些不是整数。但它们是必要的(它们有助于计算记录大小)有没有办法跳过带有"****"的行。

以下是文件中的数据:

3
4
2029
23
45
459
***
1
2
2015
3
4
20
***

当数据移动到数组并显示时,它会显示:

3
4
2029
23
45
459
***
459
459
459
459
459
459
***

这是代码:

DataBlock *writetoarray(string uname)
{
    int size;
    int data;
    size = SizeOfArray(uname);
    cout << "size:" << size << endl;
    DataBlock *ptr = new DataBlock[size];
    ifstream displayf;
    displayf.open(uname.c_str());
    int i = 0;
    for (int i = 0; i < size; i++)
    {
        displayf >> data;
        //istream& getline(displayf >> data);
        ptr[i].date = data;
        cout << ptr[i].date << endl;
        displayf >> data;
        ptr[i].month = data;
        cout << ptr[i].month << endl;
        displayf >> data;
        ptr[i].year = data;
        cout << ptr[i].year << endl;
        displayf >> data;
        ptr[i].hrs = data;
        cout << ptr[i].hrs << endl;
        displayf >> data;
        ptr[i].min = data;
        cout << ptr[i].min << endl;
        displayf >> data;
        ptr[i].bgl = data;
        cout << ptr[i].bgl << endl;
        displayf >> data;
        cout << "***" << endl;
    }
    displayf.close();
    return ptr;
}//function ends

我搜索了很多,但找不到解决方案。明天是提交日期。如果您能帮助我,我将不胜感激。如果需要任何进一步的信息,请告诉我。

添加更多详细信息:这是数据块代码:

struct DataBlock
{
    int date, month, year, hrs, min, bgl;
};

对于文件迭代,最好使用 getline 函数。尝试以下方法,看看它是否对您有帮助:

 std::string fileLine;
 while(!displayf.eof()) //Will navegate in the file until it reachs the end.
 {
      getline(displayf, fileLine);
      //Now your file data is in fileLine variable
     /*Do what your need with the data here*/
 }

对于 while 循环的每个插入,fileLine 将有一行文件,当文件到达其末尾时,循环将自动结束。

问题以这种方式解决:

这是

造成问题的星号,因为它们不是 int,但用于提取行的变量是 int 类型

在提取星星后添加这个解决了问题:

displayf >> data;
        if (displayf.failbit)
        {
            cout << "***" << endl;
            displayf.clear();
            displayf.ignore(numeric_limits<streamsize>::max(), 'n');
        }