PAYROLL HELP ME PLEASSEE! Due by tuesday

The user will be prompted to enter the following data:
Name
Hours worked
Hourly wage
Amount of withheld for retirement
Tax rate
Tax rate will be entered as a whole number but is actually a percentage.

Section 2
The following info will be calculated:
Overtime
Gross pay
Tax amount
Net pay
All information in Section 2 will be sent to a file. The filename is to be payrollstudentname.txt Information in the file will appear in the following format/ order.
There will be five spaces between each item of data but all information for one employee will appear on one line:
Employee name Hours worked hourly wage retirement withhold Overtime

The following data will also be printed to the screen for the employee to see:
Tax amount
Gross pay
Net pay
Please include a brief statement telling what each number represents.
At the beginning of the program the user will be asked how many employees they want to process.
A loop will be included that process employees until the number processed equals the number of employees that the user entered at the beginning of the program
No output will appear on the screen all output will be sent to the file
Last edited on
What do you need help with? Show what work you have done so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#define MAX_WEEKLY_HOURS 40
#define MAX_NAME_LENGTH 100
#define FILE_NAME "payrollstudentname.txt"

#if defined __MINGW32__ || defined __MINGW64__ || defined _WIN32 || defined _WIN64
#include <windows.h>
#define CLEAR() system("cls")
#else
#define CLEAR() 
#endif

#include <iostream>
#include <fstream>



typedef struct 
	{
		char name[MAX_NAME_LENGTH];	
		int hoursWorked;
		int hourlyWage;
		int tax;
	} EmployeeInfo;


void promptInfo(EmployeeInfo* pInfo)
{
	std::cout << "Name: ";
	std::cin.sync();
	std::cin.getline(pInfo->name,sizeof(pInfo->name));
	
	std::cout << "Hours Worked: ";
	std::cin >> pInfo->hoursWorked;

	std::cout << "Hourly Wage: ";
	std::cin >> pInfo->hourlyWage;

	std::cout << "Tax Rate (0-100): ";
	std::cin >> pInfo->tax;

	//TODO(stav): beware of unexpected input
}

void writeToFile(EmployeeInfo* pInfo)
{
	int overtime = 
		pInfo->hoursWorked>MAX_WEEKLY_HOURS?pInfo->hoursWorked-MAX_WEEKLY_HOURS:0;
	int overtimePay = overtime!=0?overtime*(pInfo->hourlyWage*0.5):0;
	int grossPay = (pInfo->hourlyWage * pInfo->hoursWorked)+overtimePay;
	int taxAmount = grossPay*(0.01*pInfo->tax);
	int netPay = grossPay-taxAmount;
	
	
	std::cout << std::endl;
	std::cout << "--Result--" << std::endl;
	std::cout << "Gross Pay: " << grossPay << '$' << std::endl;
	std::cout << "Taxes: " << taxAmount << '$' << std::endl;
	std::cout << "Net Pay: " << netPay << '$' << std::endl;
	std::cout << std::endl;

	std::cout << "Press enter to save.";
	std::cin.sync();
	std::cin.get();


	std::ofstream ofs(FILE_NAME,std::ofstream::app);
	ofs << pInfo->name << "     ";
	ofs << pInfo->hoursWorked << "     ";
	ofs << pInfo->hourlyWage << "     ";
	ofs << overtime << '\n';
	ofs.flush();
	ofs.close();
	
}

int main()
{
	CLEAR();
	EmployeeInfo info = {0};
	
	int numEmployees;
	std::cout << "Enter amount of employees you wish to process:";
	std::cin >> numEmployees;
	std::cout << std::endl;
	CLEAR();


	for(int i = 0;i<numEmployees;i++)
	{
		std::cout << "Please Enter Information Of Employee #" << (i+1) << std::endl;
		promptInfo(&info);
		writeToFile(&info);	
		CLEAR();
	}	

	std::cout << "All info saved. thank you." << std::endl;



	return 0;
}
Last edited on
Okay, now tell us what isn't working.

That is some weird mixing of C and C++-style code.
I've never seen std::cin.getline used before.

For some reason, I also needed to put an std::cin.ignore statement after entering the number of employees, to get std::cin.getline to work properly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <limits>

int main()
{
	CLEAR();
	EmployeeInfo info = {0};
	
	int numEmployees;
	std::cout << "Enter amount of employees you wish to process:";
	std::cin >> numEmployees;
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	std::cout << std::endl;
	CLEAR();
}


I would suggest using C++ strings instead of char arrays.

1
2
3
4
5
6
int main()
{
    std::string name;
    std::getline(std::cin, name);
    std::cout << "Name = " << name;
}
Last edited on
oh sorry,
im not the guy who asked the question.

i just decided to write the program as an exercise, for myself.
and then i thought, i might as well post the code in case he can use it.

Thanks for the advice, though, i changed all the char arrays to strings :D
is there anything else that im doing in an odd way?

(for instance, im not really sure if the way i made the employeeInfo struct is correct?
Im not sure why people even typedef structs in the first place. I just know that in the winapi's structs are typedefs for some reason, so i decided to do it too)

not sure what the deal is with the cin.ignore. i think i'll try to read up on iostreams.


Last edited on
@stav,
In C++ it's better to use const or constexpr for constants.
1
2
3
4
5
6
7
8
9
#define MAX_WEEKLY_HOURS 40
#define MAX_NAME_LENGTH 100
#define FILE_NAME "payrollstudentname.txt"

//could become

const int MAX_WEEKLY_HOURS  = 40;
const int MAX_NAME_LENGTH = 100;
const std::string FILE_NAME = "payrollstudentname.txt";


Also it's better to references instead of pointer.
1
2
3
void writeToFile(EmployeeInfo* pInfo)
//could become
void writeToFile(const EmployeeInfo& Info)


Also file streams will close and flush automatically when to go out of scope.
Like @stav, I also worked through this for practice.

This is what I could come up with really quick, might have to split the code into separate posts...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Pre-processors.

#include<cctype>
#include<cstring>
#include<float.h>
#include<fstream>
#include<iomanip>
#include<iostream>

using namespace std;

// Constants.

const int MAX = 100;  // Arbitrary maximum.
const int NAME = 16;  // Available size for Emp.'s name.


// Prototypes.

void welcome_user();  // Welcome the user to the program.
void cls();           // Clears the screen of text.
void add_user();      // Get the user's info.
void calculate(char[], float, float, float, float, float);     // Calculate the Emp.'s pay.
bool writeout(char [], float, float, float, float, float);     // Write out Employee data.


// Function Implementations.

void cls()  // Clear the screen of text.
{
    for(int i = 0; i < 30; i++)
        cout << "|" << endl;
}

void welcome_user() // Welcome user to the program.
{ cout << "| welcome to the program!" << endl << endl << endl; }



int main()
{
    welcome_user();

     int num_to_enter;

     cout << " How many employees would you like to input? : ";
     cin >> num_to_enter;
     cin.ignore(MAX, '\n');

     for(int i = 0; i < num_to_enter; i++)
     {
        cls();
        add_user();
     }

}



// Get employee information.

void add_user()
{
    char uname[NAME];                      // Employee's name.
    float ehours, ewage, overtime = 0.00;  // Employee data.
    float etax_rate, retirement;           // Withholdings.


    cout << "| > Enter the employee's name: ";
    cin.get(uname, NAME, '\n');
    cin.ignore(NAME, '\n');

    cls();

    cout << "| > Enter " << uname << "'s hourly wage: $ ";
    cin >> ewage;
    cin.ignore(MAX, '\n');

    cls();

    cout << "| > Number of hours worked: ";
    cin >> ehours;
    cin.ignore(MAX, '\n');

    cls();

    cout << "| What is the Income Tax Rate? (as a %)      " << endl
         << "| Ex: 2 = 2.00% (0.02), 0.25 = 0.25% (0.0025)" << endl
         << "| > : % ";
    cin >> etax_rate;
    cin.ignore(MAX, '\n');

    etax_rate = (etax_rate / 100);      // Convert percentage to decimal.

    cls();

    cout << "| How much should be withheld for retirement? (USD)" << endl
         << "|    Ex: $ 1, $ 15.00, $ 1305.90               " << endl
         << "| > : $ ";
    cin >> retirement;
    cin.ignore(MAX, '\n');

    calculate(uname, ehours, ewage, etax_rate, retirement, overtime); // Calculate & write.
}




// Run calculations for this iteration (employee).

void calculate(char empname[], float hours, float wage, float tax_rate, float retire, float ot)
{
        cout << " Calculating..." << endl << endl << endl;

        float total_wage, wage_aftholds;   // Wage before & after withholdings.
        float ot_wage = 0.00, taxes_held;

        if(hours > 40)                      // If the employee earned OT...
        {
            int selection;
            do
            {
                cout << "| >> Overtime detected << " << endl
                     << "| How much is overtime?   " << endl
                     << "|------------------------ " << endl
                     << "| 1) Time & 1/4           " << endl
                     << "| 2) Time & 1/2           " << endl
                     << "| 3) Double Time          " << endl
                     << "|------------------------ " << endl
                     << "| : ";
                cin >> selection;
                cin.ignore(MAX, '\n');

                switch(selection)
                {
                case 1:
                    ot_wage = wage * 1.25;     // Set time & a quarter.
                    break;
                case 2:
                    ot_wage = wage *  1.50;    // Set time & a half.
                    break;
                case 3:
                    ot_wage = wage *  2.00;    // Set double-time.
                    break;
                default:                       // Handle invalid input.
                    cls();
                    cout << " Invalid selection. Please try again." << endl << endl << endl;
                }

            }while(!(selection > 0 && selection < 4));

            ot = (hours - 40) * ot_wage;           // Calculate the overtime earned ($).

            total_wage = (wage * 40) + ot;         // Calculate pay including OT.
        }
        else                                // If not...
        {
            ot = 0.00;
            total_wage = (hours * wage);        // Calculate the pay earned.
        }

        // Calculate withholdings.
        wage_aftholds = total_wage - ((total_wage * tax_rate) + retire);

        // Calculate taxes($) withheld.
        taxes_held = total_wage * tax_rate;


        cout << endl << " Calculations finished! " << endl << endl << endl;

        cls();


        char choice;                    // Output zee results!

        cout << "|====================================== " << endl
             << "| Employee: " << empname                  << endl
             << "|-------------------------              " << endl
             << "| Hourly Wage: $ " << wage   << " / hr  " << endl
             << "|-------------------------              " << endl
             << "| Tax Rate:      " << tax_rate * 100 << " %" << endl
             << "|====================================== " << endl
             << "|           This pay period             " << endl
             << "|- - - - - - - - - - - - - - - - - - -  " << endl
             << "|                                       " << endl
             << "| > Pay (pre-tax):   $ " << total_wage    << endl
             << "|                                       " << endl
             << "| > Pay earned:      $ " << wage_aftholds << endl
             << "|                                       " << endl
             << "|- - - - - - - - - - - - - - - - - - -  " << endl
             << "| > Hours worked: " << hours              << endl
             << "| > Overtime earned: $ " << ot            << endl
             << "|   OT ratio (%):    $ " << ot_wage       << endl
             << "|                                       " << endl
             << "| Withholdings:                         " << endl
             << "|  > Retirement:    -$ " << retire        << endl
             << "|  > Taxes:         -$ " << taxes_held    << endl
             << "|====================================== " << endl
             << "|                                       " << endl
             << "| >>> Save to file? (y/n): ";
         cin >> choice;
         cin.ignore(MAX, '\n');

         choice = tolower(choice);

        if(choice == 'y')
        {
             bool handler = NULL;

             do             // Loops in case the file couldn't be connected to.
             {
                   // Write out the data.
                   handler = writeout(empname, hours, wage, retire, taxes_held, ot);

             }while(!handler);

             cls();
             cout << "| >>> Data successfully saved! " << endl << endl << endl;
        }
        else
            cout << " Confirmed. Returning..." << endl << endl << endl;
}
Lastly, the function that writes the data to the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Write the employee information to a file.

bool writeout(char name[], float hrs, float perhour, float savings, float tholds, float overt)
{
    ofstream file_out;

    file_out.open("payroll.txt", ios_base::app);    // Open the file & append to it.

    if(file_out)                                    // If successfully connected to file...
    {
        file_out << name    << "     "                  // Write out employee data.
                 << hrs     << "     "
                 << perhour << "     "
                 << savings << "     "
                 << tholds  << "     "
                 << overt   << "     "
                 << endl;

        file_out.close();                               // Close file & clear any flags.
        file_out.clear();

        return true;                                    // Return successful.
    }
    else                                            // If connection unsuccessful...
    {
        char choice;

        cout << "| >>> Error. Could not connect to file... " << endl
             << "| Try again? (y/n): ";
        cin >> choice;
        cin.ignore(MAX, '\n');

        choice = tolower(choice);

        if(choice == 'y')
            return false;              // Return unsuccessful (meaning try again).
        else
            return true;               // Don't try again.
    }
}


These should do pretty much exactly what you asked.

I'm guessing this is for homework, so just be warned that this program doesn't handle every case. For example, it doesn't check that the amount withheld for retirement is not greater than the pay earned; nor does it check any ranges for input values (i.e. taxes > 100%, hourly wage = $1,000,000, etc.).
I know that these are things my professor would make note of so I thought it'd be worth mentioning, but it should be more than enough to get you started!
Let me know if it needs any further explaining.

Hope it helps!
Registered users can post here. Sign in or register to post.