c++file-ioifstreamgetlineistream

istream::getline return type


What does the istream::getline method return?

I am asking because I have seen that to loop through a file, it should be done like this:

while ( file.getline( char*, int ) )
{
    // handle input
}

What is being returned?


Solution

  • It returns a stream so that we can chain the operation.

    But when you use an object in a boolean context the compiler looks for an conversion operator that can convert it into a type that can be used in the boolean context.

    C++11

    In this case stream has explicit operator bool() const. When called it checks the error flags. If either failbit or badbit are set then it returns false otherwise it returns true.

    C++03

    In this case stream has operator void*() const. As this results in a pointer it can be used in a boolean context. When called it checks the error flags. If either failbit or badbit are set then it returns NULL which is equivalent to FALSE otherwise it returns a pointer to self (or something else valid though you should not use this fact)).

    Usage

    So you can use a stream in any context that would require a boolean test:

    if (stream >> x)
    {    
    }
    
    while(stream)
    {
        /* do Stuff */
    }
    

    Note: It is bad idea to test the stream on the outside and then read/write to it inside the body of the conditional/loop statement. This is because the act of reading may make the stream bad. It is usually better to do the read as part of the test.

    while(std::getline(stream, line))
    {
        // The read worked and line is valid.
    }