Reputation: 79
I am working on a project for my class. And I have gotten the entire thing to work, except one part. I am reading integers in from a file and turning them into a bankQueue, and eventList. I have to do this one line at a time.
My file looks like this.
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);
That is my first code which works to store the first line of data into the 2 variables. The problem I have is when I go to add the next line later on. The following code is in a different function than the code above.
if (!inFile.eof())
{
tempArrivalEvent.type = ARRIVAL;
inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;
anEventList.insert(tempArrivalEvent);
} // end if
The second code ends up taking the same exact line of data in as the first one. I need it to jump down to the next line but I can't figure it out. This is the only thing stopping my project from working.
Upvotes: 0
Views: 80
Reputation: 66224
First and foremost, you're completely ignoring the potential failure of the actual read extractions of your two formatted inputs. It is beyond-easy to validate simply by examining the state of the istream as a result of the extraction. your first case then becomes:
tempArrivalEvent.type = ARRIVAL;
if (inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength)
eventList.insert(tempArrivalEvent);
Secondly, and likely more related to your code as-presented, consider this. inFile.eof()
will not present true
until you've attempted to read beyond EOF once you've arrived there (assuming all things have been successful until then). Therefore this code is not correct either:
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
This should be... exactly the same as the initial read. Validate the extraction success and only-then perform the event list insertion.
tempArrivalEvent.type = ARRIVAL;
if (inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength)
anEventList.insert(tempArrivalEvent);
Note: All of this assumes inFile
is the same ifstream
object in both extraction code slices. You've not clarified whether you're passing the first-case inFile
by-reference to the second case in a different function. You need to pass it by-reference (or , shudder, use a global) if you want consecutive reads to work correctly.
Upvotes: 1