2013-12-07 2 views
0

Большая картинка должна взять информацию из одного файла в другой файл. Я сделал это, и он работает хорошо. Следующее, что мне нужно сделать, это найти максимальное значение из нового файла. Основной формат таков: у меня есть куча «рабочих», у меня есть дни, когда они работали, часы & минут, с которыми они работали. В новом файле я отформатировал его, чтобы показать ставку оплаты (я ввожу значение как cin), а затем у меня есть общая сумма денег, которую они сделали (каждый делает ту же сумму .. то, что находится в cin). По какой-то причине я не могу сделать функцию (которая работает), которая будет извлекать имя человека, которое делает больше всего денег, и сколько денег. Я немного расстроился и старался изо всех сил, чтобы новая функция была неаккуратной и смешной, но я надеялся, что вы сможете помочь. Чтобы удержать этот общий вопрос, а не конкретный вопрос, мне было интересно, могли бы вы, ребята, просто объяснить, как сделать что-то подобное (найти наивысшее значение &, выводя его с именем человека .. так что, по сути, это двойное значение для денег и строка с именем человек), используя части моего кода в качестве примера:двойные функции, fstream, и больше удовольствия

#include <iostream> 

    #include <fstream> 

    #include <iomanip> 

    #include <string> 

    #include <cstdlib> 

    using namespace std; 

    void getandprintaddress (ifstream&, ofstream&); // this function will be used to get the data from one file and input it into the next with the total amount of money made from each person as well as the next function 
    double highestpaid(double& highesttotal, double& totalpay, string highestpaidemp, string name); // this function is what will be used to find the highest amount of money and the person who has it 
    void name(); // This is to input my name in the file. 

    struct employees // This is the structure with all of the information that will be used to calculate everything. 
    { 
    string name; // person's name 
    string highestpaidemp; // highest paid employee 
    string address; // the address of the employee 
    string address2; 
    int days; // days worked 
    int hours; //hours worked 
    double minutes; // minutes worked 
     int total_hours; // total hours worked 
    double totalpay; // total pay 
    double payrate; // pay rate 
    double total_minutes; // minutes worked 
    double total_time; // total hours and minutes worked 
    double highesttotal; // the highest total amount of money made between all employees. 

}; 

int main(){ 
    ifstream inputFile; 
    ofstream outputFile; 
    getandprintaddress(inputFile, outputFile); 



return 0; 
} 

void getandprintaddress(ifstream& inputFile, ofstream& outputFile) // the main function that will be used to get and output all the information. 
    { 
     struct employees(); 
     ifstream getdata; 
     ofstream outdata; 
     int employees_t; 

     employees employeeinfo; 

     string inputfile; 
     string outputfile; 

cout << "What is the name of your input file? "<<endl; // this will be the file you open 
      cin>>inputfile; 


    getdata.open(inputfile.c_str()); 


    if(getdata.fail()){ // this is meant to be used if someone enters a file that isn't there 
      cout << "The input file has failed to open. \n"; 
      exit(1); 
    } 


    cout << "What is the name of your output file? \n"; // what you want the title of the new file to be. 
       cin>>outputfile; 
       outdata.open(outputfile.c_str()); 


if(outdata.fail()) 
{ 
    //This is if the new file is invalid 

    cout << "The outputfile failed to open. \n"; 
    exit(1); 


} 


    cout << "How many employees are there? \n" ; 
        cin >> employees_t; // Enter how many employees there are 

    cout << "What is the employees hourly payrate? \n"; 
        cin >> employeeinfo.payrate; // how much each employee makes. 

    for (int info = 0; info < employees_t; info++) 
     { 
      employeeinfo.highesttotal = 0.0; // this will be needed for calculating the highest paid employee 

      employeeinfo.total_minutes = 0.0; // This is needed to calculate total minutes 

      employeeinfo.total_hours = 0; // Same as the total_minutes, but for hours instead. 

      employeeinfo.total_time = 0.0; // Needed to calculate total time 

      string line1; 

      getline(getdata, employeeinfo.name); 

      outdata << "Name: " << employeeinfo.name <<endl; // employees name 

      getline(getdata, employeeinfo.address); 

      outdata << "Address: \n"; // Employees address 

      outdata<< employeeinfo.address <<endl; 

      getline(getdata, employeeinfo.address2); 

      outdata <<employeeinfo.address2 <<endl; 

      getdata >> employeeinfo.days; 

      outdata << "Days worked: " <<employeeinfo.days << endl; // Days worked 

      for (int totalworked=0; totalworked<employeeinfo.days; totalworked++) 
       { 
        // Because the employees work different amount of days, this loop is needed to post the individual information from each employee 

        getdata >> employeeinfo.hours >> employeeinfo.minutes; 

        employeeinfo.minutes = employeeinfo.minutes/60; 

        employeeinfo.total_hours = employeeinfo.total_hours + employeeinfo.hours; 

        employeeinfo.total_minutes = employeeinfo.total_minutes + employeeinfo.minutes; 

        employeeinfo.total_time = employeeinfo.total_minutes + employeeinfo.total_hours; 

        employeeinfo.totalpay = employeeinfo.total_time * employeeinfo.payrate; 

        outdata << employeeinfo.hours <<" hours "<< employeeinfo.minutes*60 << " minutes"<< endl; 

       } 
      outdata << fixed << showpoint << setprecision(1); // Setting the total hours worked to 1 decimal so that to include the minutes 

      outdata << "Total hours worked: "<<employeeinfo.total_time<<endl; // Total hours worked 

      outdata << fixed << showpoint << setprecision(2); // Setting the decimal to two places 

      outdata << "Hourly pay: $"<<employeeinfo.payrate << endl; //Hourly pay 

      outdata << "Gross pay: $" <<employeeinfo.totalpay <<endl; // Gross pay 

      getline(getdata,line1); 

      getline(getdata,line1); 

      outdata << "\n"; 

      double highestpaid(employeeinfo.highesttotal, employeeinfo.totalpay); 
     } 

    }; 
double highestpaid(double& highesttotal, double&totalpay, string highestpaidemp, string name) 
    { 

     if (highesttotal < totalpay) 
     { 
      highesttotal = totalpay; 
      highestpaidemp = name; 


     } 

return highestpaid(double& highesttotal, double&totalpay, string highestpaidemp, string name); 
    }; 
+0

как отформатирован файл? можете ли вы отложить свой код и добавить комментарии? его довольно трудно читать. – elyashiv

+0

Да, извините! Мне все равно нужно было это сделать. – Tyler

ответ

0

Ок, я собираюсь ответить на ваш вопрос общего характера, а не тратить слишком долго рыться в вашем коде, но мы надеемся, должны работать и то и другое.

У вас есть ваша структура сотрудник

Придерживайтесь их все в векторе сотрудников (которые я буду называть рабочий)

vector<struct employee> workers 

с использованием вектора означает, что вы можете просто продолжать добавлять больше к концу , но массив работал бы также, если бы у вас было фиксированное количество рабочих

теперь каждый рабочий может быть идентифицирован целым индексом, от 0 до n-1, где n - количество рабочих. Теперь можно просто перебирать (быстрее методы, если очень большое количество рабочих, но, вероятно, хорошо здесь), чтобы найти самую высокую зарплату

double highestPay = 0; 
int highestPaidIndex = 0; 
for(int i = 0; i++; i < n) 
{ 
    if(workers[i].totalpay > highestPay) 
    { 
     highestPay = workers[i].totalpay; 
     highestPaidIndex = i; 
    } 
} 

Теперь highestPaidIndex является показателем высшего наемного работника, который имеет рабочие имя [highestPaidIndex] .name и общие рабочие доходы [highestPaidIndex] .totalpay

Надежда, которая решает как ваши общие и конкретные вопросы

+0

Я раньше не работал с векторами, но, похоже, это действительно отличная идея. Когда я делаю вектор, что мне нужно сделать, чтобы получить все имена и информацию в нем? – Tyler

+0

поэтому вектор, который я предлагаю, состоит из структур. вы просто определяете значения любого элемента структуры в векторе. Так что, если рабочий 2 работал 10 часов, просто занимаются работниками [2] .hoursWorked = 10 (или независимо от вашего соответствующего имени переменной). Разумеется, вам нужно будет перебирать всех работников, добавляя информацию к каждому из вашего файла, инициализируя один большой вектор, контактирующие структуры, которые сами будут содержать всю информацию о каждом конкретном работнике – Zephyr

Смежные вопросы