Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does while(std::ifstream >> s) work?

Tags:

c++

stl

I've used statements such as this quite a bit in my C++ programming:

std::string s;
std::ifstream in("my_input.txt");
if(!in) {
    std::cerr << "File not opened" << std::endl;
    exit(1);
}
while(in >> s) {
    // Do something with s
}

What I want to know is, why does this work?

I looked at the return value of operator>>, and it's an istream object, not a boolean. How does an istream object somehow get interpreted as a bool value that can be put inside of if statements and while loops?

like image 733
bobroxsox Avatar asked Feb 13 '15 17:02

bobroxsox


People also ask

Does ifstream automatically close?

Note that any open file is automatically closed when the ifstream object is destroyed.

What does STD ifstream do?

std::ifstream Objects of this class maintain a filebuf object as their internal stream buffer, which performs input/output operations on the file they are associated with (if any). File streams are associated with files either on construction, or by calling member open .

How does EOF work C++?

C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data to be read from an input file stream, and zero (meaning FALSE) otherwise. Rules for using end-of-file (eof( )): 1. Always test for the end-of-file condition before processing data read from an input file stream.


1 Answers

The base class std::basic_ios provides an operator bool() method that returns a boolean representing the validity of the stream. For example, if a read reached the end of file without grabbing any characters, then std::ios_base::failbit will be set in the stream. Then operator bool() will be invoked, returning !fail(), at which time extraction will stop because the condition is false.

A conditional expression represents an explicit boolean conversion, so this:

while (in >> s)

is equivalent to this

while (static_cast<bool>(in >> s))

which is equivalent to this

while ((in >> s).operator bool())

which is equivalent to

while (!(in >> s).fail())
like image 74
David G Avatar answered Sep 16 '22 15:09

David G