Answer the question
In order to leave comments, you need to log in
How to add numbers from a file if there is a certain word in the line?
We have the following "database" format:
Next, the person enters the name of the database:
After the program must find the name of this database in each line (there can be as many as you like) and add up the salary values, they are written in the format: *number
string namebase;
cout << "Okey, write name base: ";
cin >> namebase;
Answer the question
In order to leave comments, you need to log in
Although your question is similar to a task (see Rules)
But nevertheless, here
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<vector>
#include<iterator>
#include<numeric>
using namespace std;
struct Record {
string surname;
string dbname;
int salary;
};
istream& operator>>(istream& is, Record& r)
{
is >> r.surname;
is.ignore(6, '|');
is >> r.dbname;
is.ignore(6, '|');
is.ignore(6, '*');
is >> r.salary;
return is;
}
ostream& operator<<(ostream& os, const Record& r)
{
os << r.surname << " "
<< r.dbname << " "
<< r.salary;
return os;
}
int main()
{
vector<Record> database;
if(ifstream file("databasename.db"); file)
{
copy(istream_iterator<Record>(file), {}, back_inserter(database));
}
string db;
cin >> db;
int acc = accumulate(database.begin(), database.end(), 0, [&](int init, Record const& rec){
return (db == rec.dbname) ? init + rec.salary : init;
});
cout << db << ": " << acc;
//copy(database.begin(), database.end(), ostream_iterator<Record>(cout, "\n"));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question