0

I am reading an introductory book on C++. In that there is an example program on opening a file.

The code is as follows...

    #include<iostream.h>
#include<fstream.h>
void main()
{
    ifstream fin;
    fin.open("country");
    while(fin)
    {
         ....
         .....
    }
}

Here is my doubt. In the code the author says that,fin will evaluate to 0 if there are any errors in the file operation(including end-of-file condition).In this case how can an object be evaluated to an integer(i.e. 0. Or Some-non zero)?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    See: http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool (and welcome to the wonderful world of overloaded operators). – Paul R Nov 01 '16 at 16:47
  • 1
    Be aware that any errors or status will only be updated *after an I/O operation takes place*. That means that using `fin >>` to read a value then may trigger EOF. – Thomas Matthews Nov 01 '16 at 16:51
  • 4
    Note also that you might want to get a [newer/better book](http://stackoverflow.com/q/388242/253056) - `void main` is incorrect, as is the use of `` and `` (they have been obsolete for many years - it should just be `` and ``). – Paul R Nov 01 '16 at 16:51
  • 1
    Throw that book away, it is out of date by some 18 years. C++ stopped using `` in 1998. – n. m. could be an AI Nov 01 '16 at 16:57
  • Please suggest me some good books – R.S.S.H KRISHNA Nov 01 '16 at 16:58
  • 1
    [An absolute pleasure! I love suggesting good books.](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) This isn't sarcasm. You have no idea how much time it saves in the long run. – user4581301 Nov 01 '16 at 17:18

1 Answers1

2

In this case how can an object be evaluated to an integer?

By applying operator bool.

Note that the

    while(fin)

is uncommon. Instead it should be used with an input operation. The test is then testing if the input operation is successful. See for instance the linked example.

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream s("1 2 3 error");
    int n;
    std::cout << std::boolalpha << "(bool)s is " << (bool)s << '\n';
    while (s >> n) {  // Is read successful?
        std::cout << n << '\n';
    }
    std::cout << std::boolalpha << "(bool)s is " << (bool)s << '\n';
}
Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67