阅读多个列表

Reading multiple lists

本文关键字:列表      更新时间:2023-10-16

我正在做一个项目,我需要从一个文本文件中读取多个列表。除了读取它们之外,它还报告一些基于所读入的整型数的计算。文件读取在列表开头给定的哨兵处结束。

我用来测试的列表是:
9999  //sent value
636.9 // number to be ignored
First
4
8
15
16
23
42
Second
0.0
9999

我遇到的问题是,我的代码正确地读取并存储了第一个列表的数据,但是当循环再次执行时,它没有读取第二个列表。

我的主循环是:

infile >> sent;
infile >> inX;
while (!infile.fail())
{
    inX = 0;
    while (inX != sent)
    {
        int dSize = 0;
        storeNames(listNames, infile);
        ReadData(theData, infile);
        cout << listNames[count] << endl;
        cout << "Size isttt" << theData.size() << endl;
        if (theData.size() >= 1)
        {
            ComputeStats(theData, meanValue, secondHigh);
            DisplayStats(meanValue, secondHigh);
            dSize = theData.size();
            inX = theData[dSize - 1];
        }
        theData.clear();
        count++;
    }
}

读取数据函数为:

void ReadData(vector<int>& theData, ifstream& in)
{
    if (in.is_open())
    {
        int number;
        while (in >> number)
        {
            theData.push_back(number);
        }
    }
}

最后storeNames函数是:

void storeNames(vector<string>& listNames, ifstream& in)
{
    string name;
    in >> name;
    listNames.push_back(name);
}

提前感谢您的帮助!

while (in>> number)

考虑到上面的代码,在流状态失败后,您是否恢复它?readData将消耗所有内容,之后需要恢复流的状态,如果想再次读取,则需要将seekg移回。

可以在这里找到恢复istream状态

是否需要移动seekg取决于您是否想再次使用相同的数据,否则您可能需要将流指针移动到下一个数据节。