Question

------------------------------------------------
          Artiles for a magazine          
------------------------------------------------
There are total 5 articles in the magazine
------------------------------------------------
ID : 3
Description : opis2
Price : 212
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 424
Date : 20324
------------------------------------------------
ID : 3
Description : 54
Price : 123
Incoming amount : 12
Outgoing amount : 0
Taxes : 0
Total : 1476
Date : 120915
------------------------------------------------
ID : 3
Description : opsi2
Price : 12
Incoming amount : 324
Outgoing amount : 0
Taxes : 0
Total : 3888
Date : 570509
------------------------------------------------
ID : 2
Description : vopi
Price : 2
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 4
Date : 951230
------------------------------------------------
ID : 1
Description : opis1
Price : 2
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 4
Date : 101
------------------------------------------------

I have a file called directory.dat with the contents above. What I'm trying to do is the following.

I want to find all articles with the same ID in a given year and do the following : outgoing amount - incoming amount. So, my problem is how can I find all the articles with same ID in a given year (by the user) and do the outgoing amount-incoming amount for them, by working with the file?

I tried something like this:

ifstream directory("directory.dat");
//directory.open("directory.dat");
string line;
string priceLine = "Price : ";
int price;
while(getline(directory, line)){
    if(line.find(priceLine) == 0){
        cout << atoi(line.substr(priceLine.size()).c_str()) << endl;
    }
}
cout << price << endl;
directory.close();

But I am far away from getting on the right track and I need some help to achieve something like this.

Was it helpful?

Solution

You need to define precisely the format of your input (perhaps as a BNF grammar). A single example is not enough. We can't guess if Artiles for a magazine is meaningful or not.

 while(getline(directory, line)){
    int colonpos = -1;
    if (line.find("----")) {
        /// check that line has only dashes, then
        process_dash_line();
    }
    else if ((colonpos=line.find(':'))>0) {
       std::string name = line.substr(0, colonpos-1);
       std::string value = line.substr(colonpos+1);
       process_name_value (name, value);
    }
 }

Also, study (and perhaps adapt) the source code of some free software C++ parsers for JSON (e.g. jsoncpp) and YAML (e.g. yaml-cpp). They will certainly give you some inspiration.

Learn more about C++ standard libraries, e.g. on cppreference.com & cplusplus.com (both sites are easy to read but are imperfect) and of course by reading the C++11 standard, or at least its draft n3337

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top