Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

istream (ostream) vs. bool

Tags:

c++

types

casting

Here is a C++ code which reads as many words from a given text file as possible until it meets EOF.

string text;
fstream inputStream;


inputStream.open("filename.txt");

while (inputStream >> text)
    cout << text << endl;

inputStream.close();

My question is:

  • what procedure exactly is performed behind on converting the condition of the while loop (i.e., inputStream >> text) into a boolean values (i.e., true or false)?

My own answer for the question is:

  • To my understanding, inputStream >> text is supposed to return another (file) input stream. The stream seems to be NULL when EOF arrives. The NULL may be defined as 0, which is equivalent to false.

Does my answer make sense? Even if my answer does make sense, such conversion of InputStream to bool doesn't make me so comfortable. :)

like image 419
user3509406 Avatar asked Apr 09 '14 06:04

user3509406


People also ask

Is Ostream in Iostream?

istream and ostream serves the base classes for iostream class.

How streams work in c++?

1.1 Streams C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just like water and oil flowing through a pipe). In input operations, data bytes flow from an input source (such as keyboard, file, network or another program) into the program.


1 Answers

what procedure exactly is performed behind on converting the condition of the while loop (i.e., inputStream >> text) into a boolean values (i.e., true or false)?

operator>> returns a reference to the stream.

In C++11 the reference is then converted to a bool by the stream's operator bool() function, which returns the equivalent of !fail().

In C++98 the same is achieved by using operator void*(), and the returned pointer is either NULL to indicate failure or a non-null pointer if fail() is false, which is then implicitly converted to a bool in the while evaluation.

like image 99
user657267 Avatar answered Oct 01 '22 20:10

user657267