逐行读取数据,但不是一次全部读取

Reading in data line by line, but not all at once

本文关键字:读取 一次 全部 数据 逐行      更新时间:2023-10-16

我正在为我的班级做一个项目。除了一个部分,我把整个东西都修好了。我正在从文件中读取整数,并将它们转换为bankQueue和eventList。我只能一行一行地写

我的文件是这样的。

1 5
2 5
4 5
20 5
22 5
24 5
26 5
28 5
30 5
88 3

// Get the first arrival event from the input file, and place it in eventList
tempArrivalEvent.type = ARRIVAL;
inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;
eventList.insert(tempArrivalEvent);

这是我的第一个代码,它可以将第一行数据存储到2个变量中。我遇到的问题是当我稍后要添加下一行时。以下代码位于与上述代码不同的函数中。

if (!inFile.eof())
{
    tempArrivalEvent.type = ARRIVAL;
    inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;
anEventList.insert(tempArrivalEvent);
} // end if

第二段代码最终采用与第一行完全相同的数据行。我想让它跳到下一行,但我想不出来。

首先,您完全忽略了对两个格式化输入的实际read提取的潜在失败。简单地通过检查作为提取结果的流的状态来验证它是非常容易的。第一个case变成:

tempArrivalEvent.type = ARRIVAL;
if (inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength)
    eventList.insert(tempArrivalEvent);

其次,可能与您的代码更相关,请考虑这个。inFile.eof()将不会呈现true,直到您到达 EOF之后尝试读取(假设在此之前所有事情都已成功)。因此这段代码也是不正确的:

if (!inFile.eof())  // nope, not set yet
{
    tempArrivalEvent.type = ARRIVAL;
    // both of these fail since we're at EOF, which will now be reported
    //  as such after the first failure. We, however, never check the stream
    //  status, and thus blindly insert whatever junk happened to be in the
    //  tempArrivalEvent object, likely data from a prior insert.
    inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;
    // insert unvalidated data
    anEventList.insert(tempArrivalEvent);
} // end if

这应该是…与初始读取完全相同。验证提取成功,然后执行事件列表插入。

tempArrivalEvent.type = ARRIVAL;
if (inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength)
    anEventList.insert(tempArrivalEvent);

注意:所有这些都假设inFile在两个提取代码片中是相同的 ifstream对象。您还没有澄清您是否通过引用将第一种情况的inFile传递给不同函数中的第二种情况。如果您希望连续读取正常工作,则需要通过引用(或者使用全局)传递它。