Home > Software engineering >  Why does >> operator gives error on const file in C ?
Why does >> operator gives error on const file in C ?

Time:11-07

I have this piece of code:

void NeighborsList::insertVertexes(const ifstream & inputFile)
{
    int tempS, tempT;
    for (int i = 0; i < numOfVertexes; i  )
    {
        inputFile >> tempS;
        inputFile >> tempT;
        addEdge(tempS, tempT);
    }
}

where I'm trying to get the input for a file. Once I remove the const in the function parameter - (ifstream & inputFile) it works.

CodePudding user response:

Given a const object or reference, only const operations may be performed. std::istream::operator>> is not a const operation, therefore it may not be used here.

It makes sense that std::istream::operator>> is not a const operation, because it alters the observable state of the stream. The read position on the file is changed, for example, as well as status indicators like fail and eof.

  • Related