Search code examples
c++infinite-loopifstream

Ifstream stuck on a word, creating an infinite loop


I am writing a code that gathers data from a txt file. To get to the next interesting number, I use a do-while loop. However, the first do-while loop works perfectly, but in the second one, the ifstream myfile get stuck on the word Pmax. No idea what the cause could be. =/

Here is the interesting part of the parser (I am not using XML even though it looks a bit like it):

ifstream myfile; 
string comment;
const string filename = "data";
myfile.open(filename.c_str());

do{
    myfile>>comment;
} while (comment != "</probScen>");
for (int i=0;i<numberScen;i++){
    myfile>>comment;
    double prov;
    myfile>>prov;
    probScen.push_back(prov);
}

do{
    if(myfile.eof()){cout<<"EoF reached"<<endl;}
    myfile>>comment;
} while (comment != "</Pmax>");
for (int i=0;i<H;i++){
    myfile>>comment;
    double prov;
    myfile>>prov;
    Pmax.push_back(prov);
}

And here is the part of the txt file I want to read:

<probScen> scenario s - happening probability </probScen>
1 1
<Pmax> hour h - max price for this hour </Pmax>
1 5

The first do-while loop handles the probScen fine, but myfile in the second do-while gets stuck on Pmax, thus creating an infinite loop. To be more precise, myfile reads every single word until /probScen, then 1, 1, Pmax but then does not move on anymore. The myfile.eof() never returns true.

Thank you in advance for your help!


Solution

  • The problem will occur as soon as numberScen is greater than 1 (one)!

    First iteration:

    for (int i = 0; i < numberScen; i++)
    {
        myfile>>comment; // consumes 1
        double prov;
        myfile>>prov;    // consumes 1
        probScen.push_back(prov);
    }
    

    Second iteration:

    for (int i = 0; i < numberScen; i++)
    {
        myfile>>comment; // consumes <Pmax>
        double prov;
        myfile>>prov;    // trying to parse 'hour', but fails!
                         // from now on, fail bit is set
        probScen.push_back(prov); // stores uninitialized value
    }
    

    Within the following while loop, as the fail bit is set, nothing is read at all, and so comment remains at the latestly consumed ""...