如何添加循环输入文件的结果?

时间:2016-07-26 18:05:15

标签: c++ if-statement while-loop ifstream

我是C ++的初学者,并使用计算出的通话率创建了一个输入文件。我能够单独计算每次通话的费用;但是,我不确定如何...

  1. 获取每次通话的结果并将它们合计在一起。

  2. 准确计算从白天到夜晚/工作日到周末的通话费用。

  3. 这是我到目前为止所拥有的。任何帮助深表感谢。谢谢!

    Call_History.txt

    out = regexp(data, '(\-?[0-9\.]*)(.*)', 'tokens', 'once');
    out = cat(1, out{:})
    
    %   '1'      'mcg/kg'   
    %   '1'      'mcg/kg'   
    %   '1'      'mcg/kg'   
    %   '0.7'    'mcg/kg/hr'
    %   '0.7'    'mcg/kg/hr'
    %   '0.5'    'mcg/kg/hr'
    %   '0.5'    'mcg/kg/hr'
    %   '0.5'    'mcg/kg/hr'
    

    代码

    $html = file_get_contents($url);
    preg_match_all('/<title>(.*?)<\/title>/s', $html, $matches);
    print_r($matches[1]);
    

2 个答案:

答案 0 :(得分:0)

  1. 创建求和变量,例如double sum = 0.0;
  2. 从输入行阅读cost后,将其添加到总和中:sum += cost;
  3. 打印总数时,请打印总和:cout << "\nTotal $" << sum << endl;

答案 1 :(得分:0)

通话记录包含价格,因此您列出的程序在第一行之后无法运行。但是,如果您像这样修改Call_History.txt,它将起作用

Mo 1330 16

Mo 815  35

Tu 750  20

We 1745 30

Th 800  45

Su 2350 30

除了简单推荐总结total变量中的所有成本之外,您还应考虑将程序重构为简单函数,例如dayOfWeek和成本因子计算只需求被置于不同的职能部门

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <map>

using namespace std;

//function to wrap the day lookup
int getDayOfWeek(string const &day) {
    //create a constant map to make lookup more convenient
    static const map<string, int> dayOfWeek = { { "Mo", 1 },{ "Tu", 2 },{ "We", 3 },{ "Th", 4 },{ "Fr", 5 },{ "Sa", 6 },{ "Su", 7 } };
    auto dayIterator = dayOfWeek.find(day);
    if (dayIterator == dayOfWeek.cend()) {
        //Couldn't find a match for a specified day
        return 0;
    }
    return dayIterator->second;
}

double getCostMultiplier(int time, int dayOfWeek) {
    const double DAYTIME = 0.40;
    const double NIGHT = 0.25;
    const double WEEKEND = 0.15;

    //evaluate day of week to make comparisons simplier and easier to read
    if (dayOfWeek > 5) {
        return WEEKEND;
    }
    else if ((time >= 800) && (time <= 1800))
    {
        return DAYTIME;
    }
    else
    {
        return NIGHT;
    }

    //default case so that if the conditions would change and there would be other cases this function would return something meaningful
    return WEEKEND;
}

int main()
{
    ifstream fin;
    fin.open("Call_History.txt");

    string day;
    int time = 0;
    int duration = 0;
    int dayOfWeek = 0;
    double cost = 0;
    double total = 0;

    // Set the numeric output formatting.
    cout << fixed << showpoint << setprecision(2);

    cout << "Day Time Duration Cost\n" << endl;

    while (fin >> day >> time >> duration)
    {
        dayOfWeek = getDayOfWeek(day);
        cost = duration * getCostMultiplier(time, dayOfWeek);
        cout << day << " " << time << " " << duration << " $" << cost << endl;

        //add cost to total
        total += cost;
    }

    cout << "\nTotal $" << total << endl;

    return 0;
}