Advertisement
Guest User

Untitled

a guest
Nov 16th, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. /* This program loads a file into an array of structs,
  2.  * and is able to sort that array by name and salary size.
  3.  */
  4.  
  5. #include <iostream>
  6. #include <fstream>
  7. #include <iomanip>
  8.  
  9. using namespace std;
  10.  
  11. struct Employee {
  12.     int id;
  13.     string firstName;
  14.     string lastName;
  15.     int salary;
  16. };
  17.  
  18.  
  19.  
  20. void opener(ifstream &reader) {
  21.     reader.open("employees.txt");
  22.  
  23.     if( reader.fail() )
  24.         cout << "The file employees.txt is not located in the program folder.\n"
  25.              << "Please put emplyees.txt in the program folder and try again." << endl;
  26. }
  27.  
  28. void getEmployees(ifstream &reader, Employee employees[], const int len) {
  29.     for( int i = 0 ; i < len ; i++ )
  30.         reader >> employees[i].id >> employees[i].firstName
  31.                >> employees[i].lastName >> employees[i].salary;
  32. }
  33.  
  34. void empPrintByName(const Employee employees[], const int len) {
  35.     for( int i = 0 ; i < len ; i++ )
  36.         cout << "ID: " << employees[i].id << " First Name: " << employees[i].firstName
  37.              << " Last Name: "<< employees[i].lastName << " Salary: " << employees[i].salary << endl;
  38. }
  39.  
  40. void sorter(Employee employees[], bool (*compare)(Employee, Employee), const int len) {
  41.     for( int i = 0 ; i < len - 1 ; i++ ) {
  42.         int minIndex = i;
  43.  
  44.         for( int j = i ; j < len ; j++ )
  45.             if( compare(employees[minIndex], employees[j]) )
  46.                 minIndex = j;
  47.  
  48.         Employee temp = employees[i];
  49.         employees[i] = employees[j];
  50.         employees[j] = temp;
  51.     }
  52. }
  53.  
  54. bool empSortByName(const Employee a, const Employee b) {
  55.     return a.lastName > b.lastName;
  56. }
  57.  
  58. bool empSortBySal(const Employee a, const Employee b) {
  59.     return a.salary > b.salary;
  60. }
  61.  
  62.  
  63.  
  64. int main() {
  65.     Employee allEmployees[6];
  66.     ifstream empReader;
  67.  
  68.     opener(empReader);
  69.     getEmployees(empReader, allEmployees, 6);
  70.  
  71.     sorter(allEmployees, empSortByName, 6);
  72.     empPrintByName(allEmployees, 6);
  73.  
  74.     sorter(allEmployees, empSortBySal, 6);
  75.     empPrintByName(allEmployees, 6);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement