class members, The loop only prints the last index

Stack around variable 'workers' was corrupted message keeps popping up. Why does the cout at the end only print out the last used input?

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
 // This program uses an array of structures to hold payroll data.
#include <iostream>
#include <iomanip>
using namespace std;

class PayInfo
{
private:
	int hours;           // Hours worked
	double payRate;      // Hourly pay rate
	double grossPay;

public:
	PayInfo()
	{
		hours = 0;
		payRate = 0;
		grossPay = 0;
	}

	void PayInfo::setHours(int hr)
	{
		hours = hr;
	}
	void PayInfo::setpayRate(double pr)
	{
		payRate = pr;
	}
	int PayInfo::getHours()
	{
		return hours;
	}
	double PayInfo::getPayRate()
	{
		return payRate;
	}
	double PayInfo::getGrossPay()
	{
		if (hours > 40)
		{
			grossPay = (payRate * 40 + (1.5 * payRate * (hours - 40)));
		}
		else
		grossPay = payRate * hours;

		
		return grossPay;
	}
};
int main()
{
	int hr;
	double pr;
	double grossPay;
	const int NUM_EMPS = 3;      
	PayInfo workers[NUM_EMPS]; 

	cout << "Enter the hours worked and hourly pay rates of " << NUM_EMPS << " employees. \n";

	for (int index = 0; index < NUM_EMPS; index++)
	{
		cout << "\nHours worked by employee #" << (index + 1) << ": ";
		cin >> hr;
		workers[NUM_EMPS].setHours(hr);
		cout << "Hourly pay rate for this employee: $";
		cin >> pr;
		workers[NUM_EMPS].setpayRate(pr);
	}

	cout << "\nHere is the gross pay for each employee:\n";
	cout << fixed << showpoint << setprecision(2);

	for (int index = 0; index < NUM_EMPS; index++)
	{
		hr =workers[NUM_EMPS].getHours();
		pr = workers[NUM_EMPS].getPayRate();
		grossPay = workers[NUM_EMPS].getGrossPay();
		grossPay = hr * pr;

		//workers[NUM_EMPS].getGrossPay();
		cout << "Employee #" << (index + 1);
		cout << ": $" << setw(7) << workers[NUM_EMPS].getGrossPay() << endl;
	}
	return 0;
}
@kretosa

In the body of main(), change the NUM_EMPS in lines 64, 67, 75, 76, 77, and 82, to index, and your program should work like you expect it to.
Last edited on
Topic archived. No new replies allowed.