Adding ints together from an input file

Viewed 57

I have a code which looks like this

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

struct Bill{
    std::string name;
    int bill_value;
};

enum Status{abnorm, norm};

bool read(std::ifstream &f, Bill &e, Status &st);


int main()
{
    std::ifstream x("inp.txt");
    if (x.fail() ) {
        std::cout << "Error!\n";
        return 1;
    }

    Bill dx;
    Status sx;
    int s = 0;
    while(read(x,dx,sx)) {
        s += dx.bill_value;
    }

    std::cout << "Today income: " << s << std::endl;
    return 0;
}

bool read(std::ifstream &f, Bill &e, Status &st){
    std::string line;
    getline(f,line);
    if (!f.fail() && line!="") {
        st = norm;
        std::istringstream in(line);
        in >> e.name;

        std::string product;
        int value;
        e.bill_value= 0;
        while( in >> product >> value) e.bill_value+= value;
    }
    else st=abnorm;

    return norm==st;
}

The input file called inp.txt and looks like this:

Joe tv 1200 mouse 50000
Peter glass 8000
Harry mouse 8200 usb 8000 headphones 98900
David book 500 800 mouspad 900
Liam phone 8000 cooler 3000 headphones 3000
Daniel laptop 700 pot 9000

The first is always the name of the customer, which follows by the product(s) he bought and its value.

For example Peter bought a glass for 8000, but David bought 2 books in two differente price.

And this is where my problem comes, because at David's line the program only return the value of the first book, and not the sum of the line, and i would like to know how much profit the shop made so i would need to calculate the sum of David's bill also.

1 Answers

Let file be

std::ifstream file;

Now, the following should work, the result is contained in accu:

int accu = 0;
for (std::string line; std::getline(file,line);)
{
    // replace non-spaces and non-digits by nothing
    // thus only spaces and digits are left
    std::string numbers = std::regex_replace(line, std::regex(R"([^\\d])"), "");

    std::stringstream ss(numbers);
    for (int price; ss >> price;)
    {
        accu += price;
    }
}

First we read the file line-by-line. For each line we strip the non-numeric characters but not spaces as we need them to separate numbers. Using a std::stringstream we extract the given numbers. Additionally, I made use of

#include <sstream>
#include <string>
#include <regex>

Version c++11 should be sufficient.

Note: whenever names or words contain other digits or numbers, the result is obviously incorrect. One could extend the regex to dismiss digits within other words to fix this partially. Otherwise, more information about the file structure is needed.

Related