user3509406
user3509406

Reputation: 409

istream (ostream) vs. bool

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. :)

Upvotes: 6

Views: 1632

Answers (2)

user3509406
user3509406

Reputation: 409

I know that my answer has been perfectly answered by user657267. But I am adding one more example to understand the answer more easily.

// evaluating a stream
#include <iostream>     // std::cerr
#include <fstream>      // std::ifstream

int main () {
  std::ifstream is;
  is.open ("test.txt");
  if (is) {           <===== Here, an example of converting ifstream into bool
    // read file
  }
  else {
    std::cerr << "Error opening 'test.txt'\n";
  }
  return 0;
}

Ref. http://www.cplusplus.com/reference/ios/ios/operator_bool/

Upvotes: 0

user657267
user657267

Reputation: 21000

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.

Upvotes: 11

Related Questions