#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;

struct Employee {
    int id;
    string name;
    double salary;
    double taxRate;

    Employee(int empId, const string& empName, double empSalary, double empTaxRate)
        : id(empId), name(empName), salary(empSalary), taxRate(empTaxRate) {}

    void display() const {
        cout << "ID: " << id << "\tName: " << name << "\tSalary: $" << salary << "\tTax Rate: " << taxRate << "%" << endl;
    }

    double calculateTax() const {
        return salary * (taxRate / 100);
    }

    void generatePayslip() const {
        cout << "Pay Slip for Employee ID: " << id << endl;
        cout << "Name: " << name << endl;
        cout << "Salary: $" << fixed << setprecision(2) << salary << endl;
        cout << "Tax Deduction: $" << fixed << setprecision(2) << calculateTax() << endl;
        cout << "Net Salary: $" << fixed << setprecision(2) << (salary - calculateTax()) << endl;
    }
};

void saveEmployeeToFile(const Employee& emp) {
    ofstream outFile("employees.txt", ios::app);
    if (outFile.is_open()) {
        outFile << emp.id << " " << emp.name << " " << emp.salary << " " << emp.taxRate << endl;
        outFile.close();
        cout << "Employee data saved successfully." << endl;
    } else {
        cout << "Error: Unable to save data to file." << endl;
    }
}

vector<Employee> readEmployeesFromFile() {
    vector<Employee> employees;
    ifstream inFile("employees.txt");
    if (inFile.is_open()) {
        int id;
        string name;
        double salary, taxRate;
        while (inFile >> id >> name >> salary >> taxRate) {
            employees.emplace_back(id, name, salary, taxRate);
        }
        inFile.close();
    } else {
        cout << "Error: Unable to read data from file." << endl;
    }
    return employees;
}

void exportToCSV(const vector<Employee>& employees) {
    ofstream csvFile("employees.csv");
    if (csvFile.is_open()) {
        csvFile << "ID,Name,Salary,Tax Rate,Tax Deduction,Net Salary" << endl;
        for (const auto& emp : employees) {
            double tax = emp.calculateTax();
            csvFile << emp.id << "," << emp.name << "," << emp.salary << "," << emp.taxRate << "%," << tax << ","
                    << (emp.salary - tax) << endl;
        }
        csvFile.close();
        cout << "Employee data exported to employees.csv." << endl;
    } else {
        cout << "Error: Unable to export data to CSV file." << endl;
    }
}

int main() {
    vector<Employee> employees = readEmployeesFromFile();
    int choice;

    do {
        cout << "Payroll Management System" << endl;
        cout << "1. Add Employee" << endl;
        cout << "2. View Employees" << endl;
        cout << "3. Update Employee" << endl;
        cout << "4. Delete Employee" << endl;
        cout << "5. Calculate Total Payroll" << endl;
        cout << "6. Calculate Average Salary" << endl;
        cout << "7. Give Raise to All Employees" << endl;
        cout << "8. Sort Employees by ID" << endl;
        cout << "9. Sort Employees by Salary" << endl;
        cout << "10. Search Employee by Name" << endl;
        cout << "11. Generate Payslip" << endl;
        cout << "12. Export Employee Data to CSV" << endl;
        cout << "13. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1: {
                int id;
                string name;
                double salary, taxRate;
                cout << "Enter Employee ID: ";
                cin >> id;
                cin.ignore();
                cout << "Enter Employee Name: ";
                getline(cin, name);
                cout << "Enter Employee Salary: $";
                cin >> salary;
                cout << "Enter Tax Rate (%): ";
                cin >> taxRate;
                employees.emplace_back(id, name, salary, taxRate);
                saveEmployeeToFile(employees.back());
                break;
            }

            case 2:
                cout << "Employee List:" << endl;
                for (const auto& emp : employees) {
                    emp.display();
                }
                break;

            case 3: {
                int id;
                cout << "Enter Employee ID to update: ";
                cin >> id;
                bool found = false;
                for (auto& emp : employees) {
                    if (emp.id == id) {
                        cout << "Enter new name: ";
                        cin.ignore();
                        getline(cin, emp.name);
                        cout << "Enter new salary: $";
                        cin >> emp.salary;
                        cout << "Enter new tax rate (%): ";
                        cin >> emp.taxRate;
                        cout << "Employee data updated successfully." << endl;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    cout << "Error: Employee with ID " << id << " not found." << endl;
                }
                break;
            }

            case 4: {
                int id;
                cout << "Enter Employee ID to delete: ";
                cin >> id;
                auto it = remove_if(employees.begin(), employees.end(), [id](const Employee& emp) {
                    return emp.id == id;
                });
                if (it != employees.end()) {
                    employees.erase(it, employees.end());
                    cout << "Employee deleted successfully." << endl;
                } else {
                    cout << "Error: Employee with ID " << id << " not found." << endl;
                }
                break;
            }

            case 5: {
                double totalPayroll = 0;
                for (const auto& emp : employees) {
                    totalPayroll += emp.salary;
                }
                cout << "Total Payroll: $" << fixed << setprecision(2) << totalPayroll << endl;
                break;
            }

            case 6: {
                if (!employees.empty()) {
                    double totalSalary = 0;
                    for (const auto& emp : employees) {
                        totalSalary += emp.salary;
                    }
                    double averageSalary = totalSalary / employees.size();
                    cout << "Average Salary: $" << fixed << setprecision(2) << averageSalary << endl;
                } else {
                    cout << "No employees found." << endl;
                }
                break;
            }

            case 7: {
                double raisePercent;
                cout << "Enter raise percentage: ";
                cin >> raisePercent;
                for (auto& emp : employees) {
                    emp.salary += emp.salary * (raisePercent / 100);
                }
                cout << "All employees received a " << raisePercent << "% raise." << endl;
                break;
            }

            case 8:
                sort(employees.begin(), employees.end(), [](const Employee& emp1, const Employee& emp2) {
                    return emp1.id < emp2.id;
                });
                cout << "Employees sorted by ID." << endl;
                break;

            case 9:
                sort(employees.begin(), employees.end(), [](const Employee& emp1, const Employee& emp2) {
                    return emp1.salary < emp2.salary;
                });
                cout << "Employees sorted by Salary." << endl;
                break;

            case 10: {
                string keyword;
                cout << "Enter name keyword to search: ";
                cin.ignore();
                getline(cin, keyword);
                cout << "Employees matching the keyword:" << endl;
                bool found = false;
                for (const auto& emp : employees) {
                    if (emp.name.find(keyword) != string::npos) {
                        emp.display();
                        found = true;
                    }
                }
                if (!found) {
                    cout << "No employees found with the keyword: " << keyword << endl;
                }
                break;
            }

            case 11: {
                int id;
                cout << "Enter Employee ID to generate payslip: ";
                cin >> id;
                bool found = false;
                for (const auto& emp : employees) {
                    if (emp.id == id) {
                        emp.generatePayslip();
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    cout << "Error: Employee with ID " << id << " not found." << endl;
                }
                break;
            }

            case 12:
                exportToCSV(employees);
                break;

            case 13:
                cout << "Exiting program. Goodbye!" << endl;
                break;

            default:
                cout << "Invalid choice. Please try again." << endl;
        }
    } while (choice != 13);

    return 0;
}
 

C++ Online Compiler

Write, Run & Share C++ code online using OneCompiler's C++ online compiler for free. It's one of the robust, feature-rich online compilers for C++ language, running on the latest version 17. Getting started with the OneCompiler's C++ compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C++ and start coding!

Read inputs from stdin

OneCompiler's C++ online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.

#include <iostream>
#include <string>
using namespace std;

int main() 
{
    string name;
    cout << "Enter name:";
    getline (cin, name);
    cout << "Hello " << name;
    return 0;
}

About C++

C++ is a widely used middle-level programming language.

  • Supports different platforms like Windows, various Linux flavours, MacOS etc
  • C++ supports OOPS concepts like Inheritance, Polymorphism, Encapsulation and Abstraction.
  • Case-sensitive
  • C++ is a compiler based language
  • C++ supports structured programming language
  • C++ provides alot of inbuilt functions and also supports dynamic memory allocation.
  • Like C, C++ also allows you to play with memory using Pointers.

Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
   //code
}
else {
   //code
}

You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to If-Else-If ladder.

switch(conditional-expression){    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
......    
    
default:     
 code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
  //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
// code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
 // code 
} while (condition); 

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. Function gets run only when it is called.

How to declare a Function:

return_type function_name(parameters);

How to call a Function:

function_name (parameters)

How to define a Function:

return_type function_name(parameters) {  
 // code
}