filein.txt
Petya,K221,1,2,3;Vasya,K222,4,5,6;Senya,K223,7,8,0;Goga,K224,1,2,3;
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;
template<typename X = int>
struct Data
{
X one;
X two;
X three;
Data(X x1 = 0, X x2 = 0, X x3 = 0) : one{x1}, two{x2}, three{x3}
{}
};
template<typename X = int>
struct DataRecord
{
pair<string, string> text;
Data<X> data;
DataRecord(string _s1 = {}, string _s2 = {},
X _x1 = 0, X _x2 = 0, X _x3 = 0)
: text{_s1, _s2}, data{_x1, _x2, _x3}
{}
};
template<typename X = int>
istream& operator>>(istream& is, DataRecord<X>& record)
{
char c;
getline(is, record.text.first, ',');
getline(is, record.text.second, ',');
is >> record.data.one;
is >> c;
if(c == ',')
{
is >> record.data.two;
is >> c;
if(c == ',')
{
is >> record.data.three;
}
}
is >> c;
if(c != ';')
{
is.clear(ios_base::failbit);
}
return is;
}
struct DataSet
{
vector<DataRecord<>> records;
DataSet() : records{}{}
void load(string filename) noexcept;
Data<> sumsByColumns() noexcept;
};
void DataSet::load(string filename) noexcept
{
ifstream in(filename);
if(!in)
{
//...
return;
}
copy(istream_iterator<DataRecord<>>{in}, {}, back_inserter(records));
}
Data<> DataSet::sumsByColumns() noexcept
{
Data<> result;
for(const auto& rec : records)
{
result.one += rec.data.one;
result.two += rec.data.two;
result.three += rec.data.three;
}
return result;
}
int main()
{
DataSet ds;
ds.load("C:\\infile.txt");
Data<> result{ds.sumsByColumns()};
for(const auto& rec : ds.records)
{
cout << rec.text.first << '\t'
<< rec.text.second << '\t'
<< rec.data.one << '\t'
<< rec.data.two << '\t'
<< rec.data.three << '\n';// Если формат записей в файле
// построчный '\n' нужно убрать.
}
cout << "\nTotal:\t\t"
<< result.one << '\t'
<< result.two << '\t'
<< result.three << endl;
}
OUT
Petya K221 1 2 3
Vasya K222 4 5 6
Senya K223 7 8 0
Goga K224 1 2 3
Total: 13 17 12