Reputation: 209
I learn a course from coursera. In one of the lesson ther is a code which supposed to perform read and write numeric numbers from text file using vector. This is the code:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include "Student.h"
//#include ""
using namespace std;
int main()
{
/*cout << "Hello School!" << endl;
Student sarit_student("Sarit Rotshild",12345);*/
ifstream data_file("../../sarit/data.text");
istream_iterator<int> start(data_file), end;
vector<int> data(start, end);
int sum=0;
for(auto it=start; it!=end; ++it)
{
sum+= *it;
}
cout<<"sum = "<< sum<<endl;
cout<<"avg is : "<< 1.0* sum/data.size()<<endl;
return 0;235
}
The input (in the text file) is 12 15 18 23 235 However the out put that I got is not correct---> sum = 12 avg is : 2.4
Upvotes: 2
Views: 125
Reputation: 62573
std::istream_iterators
are different from 'regular' iterators. Stream iterators are single-pass. You can't use the same iterator twice - because every increment reads data from the stream, and data read from the stream is gone from the stream. But this is what you are trying to do:
vector<int> data(start, end);
for(auto it=start; it!=end; ++it)
Here iterator start
is used twice - first to populate the vector, than to iterate over stream.
To fix your problem, iterate over vector in the loop, not the (used up) stream.
Upvotes: 3