从输入文件中添加整数

问题描述 投票:1回答:1

我有一个看起来像这样的代码

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

输入文件名为inp.txt,看起来像这样:

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

第一个始终是客户的名称,后跟他所购买的产品及其价值。

例如,彼得以8000的价格购买了一杯,但大卫以两种不同的价格购买了2本书。

这就是我的问题所在,因为在David的生产线中,该程序仅返回第一本书的价值,而不是该行的总和,我想知道这家商店赚了多少利润,所以我需要也计算大卫的帐单之和。

c++ input ifstream
1个回答
0
投票

以下应该起作用:

© www.soinside.com 2019 - 2024. All rights reserved.