Question

Basic question here, I'm trying to learn the basic of iostream.

I'm told to build a function reading lines of a const istream&. i.e. validateFile(const istream& is)

I figured out that I can't use the function getline() with a const istream& as first argument. I'm wondering why. I thought I was just reading the istream, does the function getline() alters it?

Is it possible to get information from a constant stream at all?

Was it helpful?

Solution

The idea of a stream is to read some data from it sequentially, each time advancing its internal pointer. By advancing this pointer you change the stream object. You can't read from const streams (unless you const-cast them but that's something you shouldn't do).

EDIT: Actually we don't care if the actual stream object hidden behind istream interface uses some "internal pointers" or not. To be precise, the important thing is that the stream changes its state when you read it, because the next time you read it, you get a different result (you read the next thing from the stream). And if you're given a const object, it means that you're not supposed to change its state.

Also, there's a reason why you can't just get the data from the stream and not change anything. In case of file streams it's that the next thing you want to read from the stream might not even be in the memory, stream object may have to read it from the disk first, update its buffers, etc. (EDIT: But that doesn't change externally visible state of the object, so actually it's not a good argument. Read about mutable keyword to find out more.)

OTHER TIPS

It's possible to get data from a const stream, but you need to do the reading through the streambuf class that it manages:

#include <sstream>
#include <iostream>
#include <cstdio>

int main()
{
    const std::istringstream strm("Const stream");
    std::streambuf* buf = strm.rdbuf();

    char c;
    while ((c = buf->sbumpc()) != EOF)
        std::cout << c;
}

std::getline() (as well as other I/O functions) set the underlying stream state to indicate errors during parsing or formatting. This is why the streams cannot be const-qualified. Moreover, the width() of the stream is reset after certain operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top