meftim0va
11/22/2015 - 3:28 AM

Read from file and do stuff

Read from file and do stuff

#include <iostream>
#include <fstream>

using namespace std;

struct Gas
{
    int counterID;
    double quantity;
};

istream& operator>>(istream& in, Gas& g)
{
    if (in)
    {
        int id;
        double q;

        in >> id >> q;

        if (in)
        {
            g.counterID = id;
            g.quantity = q;
        }
    }

    return in;
}

// Ако трябва да четем от двоичен файл
//
// bool load (ifstream& in, Gas& g)
// {
//      if (! in) return false;
//      in.read ((char*) &g, sizeof(g));
//      return in.good();
// }

double totalForCounter (int counterID, double ppl, ifstream& in)
{
    if (!in) return 0;

    Gas gas;
    double total;

    // while (load(in, gas))
    while (in >> gas)
    {
        if (gas.counterID == counterID)
        {
            total += gas.quantity * ppl;
        }
    }

    return total;
}

double average (int counterID, ifstream& in)
{
    double avg = 0;
    if (!in) return avg;

    Gas gas;
    size_t count = 0;

    in.clear();
    in.seekg(0, ios::beg);
    if(!in) return 0;

    while (in >> gas)
    {
        if (gas.counterID == counterID)
        {
            avg += gas.quantity;
            count++;
        }
    }

    return (avg/count);
}

void writeAvg()
{
    ofstream output("file.txt", ios::ate | ios::binary);
    if (!output) return;

    size_t maxCounterID = getMaxCounterID(in);

    for (size_t i = 1; i < maxCounterID; ++i)
    {
        output.seekp((i-1)*sizeof(Gas), ios::beg);
        double a = average(i, in);
        output.write((const char*)&a, sizeof(a));
    }
}