-1

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.

Chris
  • 26,361
  • 5
  • 21
  • 42
Nadav Holtzman
  • 210
  • 4
  • 13
  • 7
    Reading from an `ifstream` _changes_ the stream. `const` variables reject change. – Drew Dormann Nov 05 '21 at 19:55
  • 2
    Remember the const is on the stream object not the actual file. To read the ifstream object must change. – drescherjm Nov 05 '21 at 19:56
  • This question may need some _clarity_. Do you understand that extracting an `int` from an `ifstream` will modify the ifstream? Do you understand what `const` does to a variable? – Drew Dormann Nov 05 '21 at 20:15

1 Answers1

2

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.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174