Answer the question
In order to leave comments, you need to log in
How to read information from a file written in a certain way and split it into arrays (working with strings)?
There is a file. It contains records of the form:
<string1>, <string2>, <number1>, <number2>, <number3>;
Records are separated by ";".
It is necessary to read all the records from the file and sum the numbers. How to do it? Help me please.
Answer the question
In order to leave comments, you need to log in
well then
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
ifstream f("./dat.txt");
for (std::string line; std::getline(f, line);) {
stringstream ss(line);
long S = 0;
for(std::string item;std::getline(ss, item,','); ) {
try{
int v = std::stoi(item);
if (v > 0) {
S += v;
}
}
catch (exception&) {
}
}
cout << S << endl;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question