c++ - Behavior of ifstream object -
i have class has istream constructor. can initialize class object ifstream object. in program open file ifstream object , use object initialize class object.
std::ifstream in(test); object1(in); object2(in);
the file contains transactions.
math 3 5 phys 3 6 phys 3 7
etc. when print data members each line gets assigned to, object1 prints line 1 , object 2 prints line 2. why?
i mention constructor takes istream object reference , in function body, calls function takes istream object reference , uses fill in data , returns istream object.
but why each initialization advance next line in file?
constructor code:
sales_data(std::istream &is) : sales_data() { read(is, *this); }
function read code:
std::istream &read(std::istream &is, sales_data &item) { double price = 0; >> item.bookname >> item.books_sold >> price; item.revenue = price * item.books_sold; return is; }
the issue line:
is >> item.bookname >> item.books_sold >> price;
when apply >> operator stream, consume input, advance stream next position , return stream.
after reading stream, if want reuse stream read, should rewind using seekg
. calling
is.seekg (0, is.beg);
on input stream after reading reset beginning.
Comments
Post a Comment