Mars
Mars

Reputation: 4995

Behavior of ifstream object

I have a class that has an istream constructor. I can initialize the class object with an ifstream object. In the program I open a file with the ifstream object and use this object to initialize the class object.

std::ifstream in(test);
object1(in);
object2(in);

The file contains some transactions.

Math 3 5
Phys 3 6
Phys 3 7

etc. Now when I print the data members that each line gets assigned to, object1 prints line 1 and object 2 prints line 2. Why?

I also will mention that the constructor takes an istream object reference and in the function body, it calls another function which also takes an istream object reference and uses it to fill in some data and returns the istream object.

But why does each initialization advance to the next line in the 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;
is >> item.bookName >> item.books_sold >> price;
item.revenue = price * item.books_sold;
return is;
}

Upvotes: 2

Views: 128

Answers (1)

Renan Gemignani
Renan Gemignani

Reputation: 2793

The issue is this line:

is >> item.bookName >> item.books_sold >> price;

When you apply the >> operator to the stream, you actually consume the input, advance the stream to the next position and return the stream.

After reading from the stream, if you want to reuse the stream you just read, you should rewind it using seekg. Calling

is.seekg (0, is.beg);

on your input stream after reading it will reset it to the beginning.

Upvotes: 3

Related Questions