C ++ reading a file using ifstream

class Person { private: string firstName; string lastName; public: Person() {} Person(ifstream &fin) { fin >> firstName >> lastName; } void print() { cout << firstName << " " << lastName << endl; } }; int main() { vector<Person> v; ifstream fin("people.txt"); while (true) { Person p(fin); if (fin == NULL) { break; } v.push_back(p); } for (size_t i = 0; i < v.size(); i++) { v[i].print(); } fin.close(); return 0; } 

Please explain how the following code snippet works? if (fin == NULL) {break;}

fin is an object on the stack, not a pointer, so it cannot become NULL. I could not find the overloaded operator == function in the ifstream class. Therefore, I cannot understand how this fragment works.

+6
source share
3 answers

The ifstream class has operator void *() (or operator bool() in C ++ 11) . This is what is called during testing (fin == NULL) .

Testing fin == NULL should be exactly the same as testing fin.fail() .

+5
source

The base classes istream and ostream have implicit function conversions that allow them to be used as a logical value; in pre-C ++ 11, the implicit conversion was void* .

It was never intended that the result of this conversion be used as a pointer, and code like fin == NULL shows an extremely poor understanding of C ++ and standard threads. The idiomatic way of writing the first loop would be to define a default constructor and operator>> for Person , and then write:

 Person p; while ( fin >> p ) { v.push_back( p ); } 

(And while I'm in: you really have to check the return value of fin.close() and not return 0 if that fails:

 fin.close(); return fin ? EXIT_SUCCESS : EXIT_FAILURE; 

.)

+3
source

This is not how streams are supposed to be used. True, this (unfortunately!) Compiles and even does the β€œright” thing. But do not write such code. The person who wrote this code probably thought he was smart.

But what they actually did exceeded the expectations of C ++ programmers by introducing a new, unconventional API, without real benefits.

This code initializes an object of type Person from the input stream. Unfortunately, by doing this, the code does not allow checking errors when reading an object. This is not good. An object must not have a constructor that accepts an input stream; it must overload operator>> .

+2
source

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


All Articles