Istream (ostream) vs bool

Here is the C ++ code that reads as many words from a given text file as possible until it encounters EOF.

string text;
fstream inputStream;


inputStream.open("filename.txt");

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

inputStream.close();

My question is:

  • Which procedure is performed exactly to convert the condition of the while loop (i.e., inputStream → text) to boolean values ​​(i.e., true or false)?

My own answer to the question:

  • In my opinion, inputStream -> text should return another (file) input stream. The stream seems NULL when the EOF arrives. NULL can be defined as 0, which is equivalent to false.

Does my answer make sense? Even if my answer makes sense, such a conversion of InputStream to bool does not make me so convenient. :)

+4
source share
2

while ( inputStream → text) (.. true false)?

operator>> .

++ 11 bool stream operator bool(), !fail().

++ 98 operator void*(), NULL , fail() - false, bool while.

+9

, 657267. , .

// 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;
}

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

0

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


All Articles