c++ - 将输入文件中的整数相加

标签 c++ input ifstream

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

#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

第一个始终是客户的姓名,后面是他购买的产品及其值(value)。

例如,Peter 花了 8000 买了一个玻璃杯,但 David 以两种不同的价格买了 2 本书。

这就是我的问题所在,因为在大卫的生产线上,程序只返回第一本书的值(value),而不是该行的总和,我想知道商店赚了多少利润,所以我需要还可以计算大卫的账单总额。

最佳答案

文件

std::ifstream file;

现在,以下内容应该可以工作,结果包含在 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;
    }
}

首先我们逐行读取文件。 对于每一行,我们删除非数字字符,但不删除空格,因为我们需要它们来分隔数字。使用 std::stringstream 我们提取给定的数字。 此外,我还利用了

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

版本 c++11 应该足够了。

注意:只要名称或单词包含其他数字或数字,结果显然是不正确的。人们可以扩展正则表达式以忽略换句话说的数字,以部分解决此问题。否则,需要有关文件结构的更多信息。

关于c++ - 将输入文件中的整数相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60800030/

相关文章:

c++ - C++中的交换函数:错误:解析模板参数列表中的错误

c++ - 通过for循环获取文件的行数

c++ - ifstream、ofstream 和 fstream 之间有什么区别?

c++ - QT - 顶部窗口

c++ - 使用 stringstream 从循环中的另一个字符串构建字符串

c++ - 如何将文件的特定部分读入私有(private)数据成员

python - Python如何检查一个句子是否包含某个词然后执行一个 Action ?

c++ - "while (c = getchar())"等价于 C++

javascript - Jquery如果密码字段为空

c++ - 正确使用 ifstream 对象作为类的成员