简体   繁体   English

该循环执行的迭代次数超出预期

[英]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. 我期望do-while循环执行4次,对于读取的文本文件的每一行执行一次,但实际上执行5次,这会导致程序稍后出现段错误。 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. 我尝试用一​​个简单的while循环替换他的do-while ,但是结果是一样的。

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: device_list.txt包含以下内容:

WirelessAdaptor
GPU
CPU
Display

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;
    }
}

除非您尝试读取的数据多于剩余数据,否则eof()不会返回true。

eof() doesn't return true until getline consumes the end. 直到getline使用完eof()才返回true。 It doesn't do this until the getline call after reading the last line. 读取最后一行之后,直到getline调用它才执行此操作。 You need to check if eof is true immediately after your getline call: 您需要在致电getline电话后立即检查eof是否为真:

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

Above the line getline(DeviceList, line); getline(DeviceList, line);行上方getline(DeviceList, line); insert cout << line.length() << endl; 插入cout << line.length() << endl; and tell us what happens. 告诉我们会发生什么。

您的文本文件可能在最后一行之后包含换行符,因此getline在循环实际结束之前读取一个空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM