Program 8-3

Post date: Apr 10, 2013 7:50:46 AM

Program 8-3

1 // This program reads employee work hours from a file and stores them

2 // in an int array. It uses one for loop to input the hours and another

3 // for loop to display them.

4 #include <iostream>

5 #include <fstream>

6 using namespace std;

7

8 int main()

9 {

10 const int NUM_EMPLOYEES = 6; // Sets number of employees

11 int hours[NUM_EMPLOYEES]; // Holds each employee's hours

12 int count; // Loop counter

13 ifstream datafile; // Used to read data from a file

14

15 // Open the data file

16 datafile.open("work.dat");

17 if (!datafile)

18 cout << "Error opening data file\n";

19 else

20 { // Input hours worked by each employee

21 for (count = 0; count < NUM_EMPLOYEES; count++)

22 datafile >> hours[count];

23 datafile.close();

24

25 // Display the contents of the array

26 cout << "The hours worked by each employee are\n";

27 for (count = 0; count < NUM_EMPLOYEES; count++)

28 { cout << "Employee " << count+1 << ": ";

29 cout << hours[count] << endl;

30 }

31 }

32 return 0;

33 }

Program Output

The hours worked by each employee are

Employee 1: 20

Employee 2: 12

Employee 3: 40

Employee 4: 30

Employee 5: 30

Employee 6: 15