逐行读取数据,但不是一次全部读取
Reading in data line by line, but not all at once
我正在为我的班级做一个项目。除了一个部分,我把整个东西都修好了。我正在从文件中读取整数,并将它们转换为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
传递给不同函数中的第二种情况。如果您希望连续读取正常工作,则需要通过引用(或者使用全局)传递它。
相关文章:
- 在一次迭代中从 txt 文件中读取多行
- 如何使用C++一次读取整个二进制文件
- 蓝牙插座只能读取一次,为什么?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 如何从文本文件中一次读取一个字符
- 尝试一次将单个字符读取到大小不确定的数组中
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 无法一次从二进制文件中读取一个 int
- 一次读取一个字节的 unicode
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- 快速简单的方法,以C++为单位一次读取一个字节的 stdin
- 尝试一次读取一个字符的矩阵
- 我如何一次读取和写3位
- 一次从二进制读取 4 个字节(C++)
- 输入迭代器可以重复读取,而输出迭代器只能写入一次
- 如何创建在 c++ 中只读取一次的初始化函数
- 缓冲的 std::ifstream 只能从磁盘读取一次 (C++)
- QTcpSocket每~0.5s才读取一次数据,即使是非常小的数据包,任何方法都可以加快速度
- 我可以(a)不通过输入迭代器写入,或者(b)只通过一个迭代器读取一次吗?
- C++ 从键盘读取一次一个字符,直到用户输入字母("A.."Z"或"a".."z')