从C ++中的文件中查找平均薪水 [英] find average salaries from file in c++

查看:131
本文介绍了从C ++中的文件中查找平均薪水的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到文件员工的平均工资

I need to find average salary from employees of file

   John Harris $50000.00
   Lisa Smith $75000.00
   Adam Johnson $68500.00
   Sheila Smith $150000.00
   Tristen Major $75800.00
   Yannic Lennart $58000.00
   Lorena Emil $43000.00
   Tereza Santeri $48000.00

我如何获取员工的薪水,以便可以找到平均工资?我设法将文件的每一行都转换成字符串,但是我不知道如何访问每个员工的薪水 我的代码是:

How can I access the salaries of the employees so that i can find the average? I have managed to get each line of a file into a string but I dont know how to access the salaries of each employee my code is:

#include<iostream>
#include<fstream>
#include<cstring>

#include<cstdlib>
using namespace std;

int main()
{
    ifstream in;
    in.open("HW6Prob2.txt");

    if(in.fail())
    {
        cout<<"ERROR: File could not open."<<endl;
        exit(1);
    }

    string word[8];

    int i=0;
    for(i=0;i<8;i++)
    {
        getline(in,word[i]);    //get line string
        out<<word[i]<<endl;
    }
    string a=word[0];
    string b=word[1];
    string d=word[3];
    string e=word[4];
    string f=word[5];
    string g=word[6];
    string h=word[7];
    cout<<a[13]<<endl;
    string sum=
    cout<<sum<<endl;

    return 0;
}

推荐答案

我建议您在阅读线条时不断添加平均值,因此只需要在薪水列表中进行一次迭代即可.

I would suggest that you keep adding the average while you read the lines, so you just iterate once through the salaries list.

int i = 0; 
float avg_salary = 0;
string line;
// get the sum while you read the lines
while(getline(in, line)) {
    // find the first salary digit position (just after the $ sign)
    int salaryStartPos = line.find('$') + 1;
    // Convert the salary string to a float with the atof method
    avg_salary += atof(line.substr(salaryStartPos, line.size()-1)
    ++i;
}
// Finally calculate the average
avg_salary = avg_salary / i;

这篇关于从C ++中的文件中查找平均薪水的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆