Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* This program loads a file into an array of structs,
- * and is able to sort that array by name and salary size.
- */
- #include <iostream>
- #include <fstream>
- #include <iomanip>
- using namespace std;
- struct Employee {
- int id;
- string firstName;
- string lastName;
- int salary;
- };
- void opener(ifstream &reader) {
- reader.open("employees.txt");
- if( reader.fail() )
- cout << "The file employees.txt is not located in the program folder.\n"
- << "Please put emplyees.txt in the program folder and try again." << endl;
- }
- void getEmployees(ifstream &reader, Employee employees[], const int len) {
- for( int i = 0 ; i < len ; i++ )
- reader >> employees[i].id >> employees[i].firstName
- >> employees[i].lastName >> employees[i].salary;
- }
- void empPrintByName(const Employee employees[], const int len) {
- for( int i = 0 ; i < len ; i++ )
- cout << "ID: " << employees[i].id << " First Name: " << employees[i].firstName
- << " Last Name: "<< employees[i].lastName << " Salary: " << employees[i].salary << endl;
- }
- void sorter(Employee employees[], bool (*compare)(Employee, Employee), const int len) {
- for( int i = 0 ; i < len - 1 ; i++ ) {
- int minIndex = i;
- for( int j = i ; j < len ; j++ )
- if( compare(employees[minIndex], employees[j]) )
- minIndex = j;
- Employee temp = employees[i];
- employees[i] = employees[j];
- employees[j] = temp;
- }
- }
- bool empSortByName(const Employee a, const Employee b) {
- return a.lastName > b.lastName;
- }
- bool empSortBySal(const Employee a, const Employee b) {
- return a.salary > b.salary;
- }
- int main() {
- Employee allEmployees[6];
- ifstream empReader;
- opener(empReader);
- getEmployees(empReader, allEmployees, 6);
- sorter(allEmployees, empSortByName, 6);
- empPrintByName(allEmployees, 6);
- sorter(allEmployees, empSortBySal, 6);
- empPrintByName(allEmployees, 6);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement