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

In my C ++ programming, I used statements like this quite a bit:

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, why does this work?

I looked at the return value of operator>> and this is an istream object, not a boolean. How is the istream object interpreted somehow as a bool value that can be placed inside if and while if loops?

+6
source share
3 answers

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

The conditional expression is an explicit Boolean conversion, so this is:

 while (in >> s) 

equivalent to this

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

which is equivalent to this

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

which is equivalent

 while (!(in >> s).fail()) 
+6
source

std::basic_ios , from which input and output streams are inherited, has a conversion function operator bool (or operator void* to C ++ 11 to circumvent the safe-bool problem, which is no longer a problem thanks to the explicit keyword).

+5
source

See std :: basic_ios :: operator bool :

This operator allows the use of streams and functions that return references to streams as loop conditions leading to C ++ idiomatic input loops, such as while(stream >> value) {...} or while(getline(stream, string)){...} . Such loops execute the loop body only if the input operation is successful.

+3
source

Source: https://habr.com/ru/post/982452/


All Articles