Problem with infile

I have an assignment where I read in data files in a specific format and then store them in an array. Putting it simply, when I read in my data file, it will read the first set of data fine. It starts with title, which I use

getline(infile,title);

and (with other things being brought in) ends with an int

infile >> qs;

I then store all of this information into an array that is of a specific class type. Then, I restart the loop, formatted as:

while(!infile.eof() || j < B) //j being the counter and B being the largest amount of items that can be stored into the array.

Well, my problem is, it won't read in the next line of data. It will literally disregard and skip what is after the last variable I recently inserted, bringing in a blank space when it should be reading a new title. It is like this:

while(!infile.eof() || j < B)
{
getline(infile,title);
......(more data input)
infile >> qs;
......(sends information to array)
j++;
}

So, since it reads in the data file wrong when it resets, it causes a segmentation fault, thus reading each set of data incorrectly after that. I tried to counter this by taking a character (char garbage) at the end of the counter, like:

......
j++;
infile >> garbage;
}

It will then continue reading the data file correctly at the expense of the first character of the title being gone. Why is that? What can I do to fix this problem or counter all of this? This assignment is due tomorrow and I've literally tried everything and looked everywhere.

Also, since a segmentation error is created when reading in the file, it never correctly reads to the end of the file and repeats itself, thus never reaching the end of the file. BUT, when I do let it read to the end correctly, it won't recognize that it is at infile.eof() and will then continue reading in the last set of data, over and over. Please help!

You need to post all of the code really. What I will say is that this is wrong:
1
2
3
4
5
6
7
8
while(!infile.eof() || j < B)
{
getline(infile,title);
......(more data input)
infile >> qs;
......(sends information to array)
j++;
}

You should never make !infile.eof() the condition clause of the loop. The reason is that EOF is not flagged until *after* the read fails. So doing it this way means that your while loop will execute for one batch of bad data at the end of the file. You need to make a test *after* you attempted to read data so you only action data that was successfully read from the stream.

Do this:
 
while(getline(infile,title),!infile.eof || j < B)

This simulates the useful behavior of the C function fgets, which can be used like so:
 
while(fgets(s,maxlen,file))

That is, it returns zero on failure, unlike getline, which of course returns a reference in order to allow method chaining.
Topic archived. No new replies allowed.