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:
My own answer for the question is:
Does my answer make sense? Even if my answer does make sense, such conversion of InputStream to bool doesn't make me so comfortable. :)
istream and ostream serves the base classes for iostream class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With