2016-12-15 35 views
1

平均工资我需要从文件找到文件在C++中

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 

我如何可以访问员工的工资的员工找到平均工资,这样我可以求其平均值?我已经得到了一个文件的每一行成一个字符串,但我不知道如何访问每个员工的工资 我的代码是:

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

尝试在C++ 11中使用'regex'。它只适合你的问题。 http://stackoverflow.com/questions/27400131/extract-numbers-from-string-regex-c http://stackoverflow.com/questions/11627440/regex-c-extract-substring – Yves

回答

2

我建议您在阅读这些行时不断添加平均值,因此您只需在薪资列表中迭代一次即可。

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; 
+0

非常感谢你的所有你的帮助。我得到它的工作! – user143

2

这看起来像一个作业,让我给你关于如何用伪代码来应对挑战的一些提示:

sum = 0 
numberOfPersons = 0 
for each line in "HW6Prob2.txt" 
    pos = find position of $ 
    salary = cut the string from pos and parse as double 

    sum = sum + salary 
    numberOfPersons = numberOfPersons + 1 
loop 

average = sum/numberOfPersons 

我希望你会觉得这有帮助!

0

您可以使用stof函数从字符串中获取浮点值。所有你需要的是弄清楚浮点的起点。在你的情况下,你可以使用position of $ + 1作为起点。使用find函数。

0

首先,你应该通过文件行迭代(至年底)来读取所有的数据:

std::string line; 
while(std::getline(file, line)) 
{ 
    // tokenize to get the last item and store it 
} 

如果您在文件结构严格定义为呈现:[FIRST_NAME] [姓氏] $ [薪水]可以读取像每个薪金条目:

​​

所提取的文本的薪水应转换为一个数字,或者存储在vector<float>或聚集为每一行。这取决于你是否还需要在某个时候获得特定的薪水。如果你用向量选项去,你可以写水木清华这样的:

salaryList.push_back(std::stof(salaryText)); 

之后,您可以计算与平均工资:

const double salarySum = std::accumulate(salaryList.begin(), salaryList.end(), 0.0); 
const double salaryMean = salarySum/salaryList.size(); 

具有工资表的好处是,你可以进一步计算其他统计数据,不仅是平均值。