S
S
Sanders Rocket2020-05-14 19:51:58
C++ / C#
Sanders Rocket, 2020-05-14 19:51:58

How to add numbers from a file if there is a certain word in the line?

We have the following "database" format:
OBZtjrX.png
Next, the person enters the name of the database:
oRMWZX4.png
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;

2. Question: Display a list of department employees whose salary is lower than the one entered from the keyboard.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-05-14
@sandersik

Although your question is similar to a task (see Rules)
But nevertheless, here

<knee blank>

#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"));
}


2. Himself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question