user360907
user360907

Reputation:

This loop is executing more iterations than is expected

I am having problems with the following code. What I expect is for the do-while loop to execute 4 times, once for each line of the text file it is reading in, but in reality is it executing five time, which is resulting in a segfault later in the program. What am I doing wrong here that's causing it to execute the extra iteration? I've tried replacing he do-while with a simple while loop but the result is the same.

int count = 0;
string devices[4];
string line;
ifstream DeviceList;
DeviceList.open("devices/device_list.txt");
do
{
 getline(DeviceList, line);
 devices[count] = line;
 count ++;
} while(!DeviceList.eof());

device_list.txt contains the following:

WirelessAdaptor
GPU
CPU
Display

Upvotes: 0

Views: 254

Answers (5)

Fred Larson
Fred Larson

Reputation: 62073

I think your loop should probably look more like this:

Edit: Added check to ignore empty lines

while (getline(DeviceList, line))
{
    if (line.length() > 0)
    {
        devices[count] = line;
        ++count;
    }
}

Upvotes: 5

icecrime
icecrime

Reputation: 76755

Your text file probably contains a line feed after the last line, so getline reads an empty string before the loop actually ends.

Upvotes: 0

Niki Yoshiuchi
Niki Yoshiuchi

Reputation: 17551

eof() doesn't return true until getline consumes the end. It doesn't do this until the getline call after reading the last line. You need to check if eof is true immediately after your getline call:

while(true)
{
  getline(DeviceList, line);
  if(DeviceList.eof())
    break;
}

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263128

Above the line getline(DeviceList, line); insert cout << line.length() << endl; and tell us what happens.

Upvotes: 0

Edward Strange
Edward Strange

Reputation: 40859

eof() won't return true until you attempt to read more data than there is left.

Upvotes: 1

Related Questions