2

I'm having some trouble parsing a file

The last two lines of the file I want to parse are:

f 814/866/896 1035/1100/989 817/965/898

[nothing, effect from \n]

This is how I read the file:

while(!inFile.eof())
{
    inFile>>sCommand;

    if(sCommand == L"#") 
    {}
    else if(sCommand == L"f")
    {
        int iPos, iTex, iNorm;
        iPos=iTex=iNorm = -1;

        for(auto face=0; face<3; ++face)
        {
            inFile>>iPos;
            --iPos;
            if(inFile.peek() == L'/')
            {
                inFile.ignore();
                inFile>>iTex;
                --iTex;
                if(inFile.peek() == L'/')
                {
                    inFile.ignore();
                    inFile>>iNorm;
                    --iNorm;
                }
            }

            objVertexIndex iObj;
            iObj.iPos=iPos;
            iObj.iTex=iTex;
            iObj.iNorm=iNorm;
            this->AddVertex(iObj);
        }
        m_MaterialIndices_C.push_back(m_CurrentMaterial);
    } //END IF

    inFile.ignore( 1000, '\n' );
} //END WHILE
inFile.close();

However, I have some trouble with that last line of the file that contains nothing. Before the last line of the file, inFile.ignore( 1000, '\n' ); will happen and I would expect std::fstream::eof() to be detected, but for some reason it's not. And apparently sCommand will still be the same command from the previous line if there is nothing on a line, which is giving me some trouble.

Is there a way to check for this? And if yes, how?

Community
  • 1
  • 1
xcrypt
  • 3,276
  • 5
  • 39
  • 63
  • 1
    Possible duplicate of: http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line In short, eof() is not guaranteed to return true when there's nothing left to read in the stream. Only when you actually attempt to read past the end it will return true. This implies you need to *read* first and see if it succeeded and only then do things with the value read. Put a read operation in the `while` condition: `while (inFile >> sCommand) { ...` – jrok May 04 '12 at 11:52
  • Read also this http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.4 and this http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5 – jrok May 04 '12 at 12:07

1 Answers1

1

Not really an answer but a comment (I don't know how to comment). If you have 2 \n after the last line with numbers eof will not trigger. I had similar problems using .eof() and might be better to check the content of what you read as a condition to keep reading or not.

MarcoS
  • 160
  • 7