istream_iterator with for loop
Hello,
I have added the following function, just for learning about stls :) . Not professional code, so please bear with me
Code:
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iostream>
#include "string"
#include <vector>
#include "sstream"
#include "iterator"
#include "algorithm"
using namespace std;
// Write your Student class here
class Student
{
public:
vector<int> scores;
int sum;
public:
Student() :scores(0), sum(0) {}
int calculateTotalScore() { return sum; }
void input()
{
string str;
std::getline(cin, str);
if (str.empty())
std::getline(cin, str);
std::stringstream ss(str);
copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(scores));
for_each(scores.begin(), scores.end(), [this](int p) {sum += p; });
//for_each(istream_iterator<int>(ss), istream_iterator<int>(), [this](int p) {sum += p; });
}
};
int main() {
int n; // number of students
cin >> n;
//cin.ignore();
Student *s = new Student[n]; // an array of n students
for (int i = 0; i < n; i++) {
s[i].input();
}
// calculate kristen's score
int kristen_score = s[0].calculateTotalScore();
// determine how many students scored higher than kristen
int count = 0;
for (int i = 1; i < n; i++) {
int total = s[i].calculateTotalScore();
if (total > kristen_score) {
count++;
}
}
// print result
cout << count;
return 0;
}
Here i have a doubt why the red commented line doesnot work !!!.
Also, my doubt about cin and getline ignoring newline..I am bit confused about the input delimiters
like lets say:
line1\nline2\nline3\n.
How the getline and cin work ? I guess entire input is read as buffer and assigned to each getline/cin ?
thanks a lot
pdk
Re: istream_iterator with for loop
That line works just fine! That's not the problem. If you're reading from a file and you read all the data, what happens to the file state? When you get to the end of the file, can you read again from the beginning? A string stream is treated 'like a file stream'.
Code:
ss.clear();
ss.seekg(0);
for_each(istream_iterator<int>(ss), istream_iterator<int>(), [this](int p) {sum += p; });
re getline/>>
getline() reads all characters up to the specified delim char (default \n) and removes the delim char.
>> ignores all prefix white space and reads the succeeding chars up to the next white space char. It doesn't remove the white space char.
Re: istream_iterator with for loop