Click to See Complete Forum and Search --> : why is the loop started a third time?


amatorc++
August 11th, 2008, 12:51 PM
conff is an opened file which contains 4 lines only

short int nubses = 0; string line;
while (conff)
{
getline(conff, line); OPT[nubses] = line.substr(4, line.size());
getline(conff, line); OPT_Vuln[nubses] = line.substr(9, line.size());
nubses++;
}

but the program goes into the loop a third time and crashes... why? it should be end of file

Philip Nicoletti
August 11th, 2008, 01:21 PM
I find that it is usually best to code these loops as follows:


while (getline(conff, line))
{
OPT[nubses] = line.substr(4, line.size());
getline(conff, line);
// should probably check stream state here also
OPT_Vuln[nubses] = line.substr(9, line.size());
nubses++;
}

Hermit
August 11th, 2008, 01:22 PM
failbit, badbit, and/or eofbit are not set until after an input operation fails, so you'll need to check after each call to getline to make sure that data was actually extracted from the stream.

I think the following should work:
short int nubses = 0; string line;
while (!conff.eof())
{
if (getline(conff, line))
OPT[nubses] = line.substr(4, line.size());

if (getline(conff, line))
OPT_Vuln[nubses] = line.substr(9, line.size());

nubses++;
}

EDIT: I like Philip's version better.

amatorc++
August 11th, 2008, 03:35 PM
thx a lot guys