need help

I am having problems with this code. I am hoping someone can help?
I am tring to get my program to open and read and calculate the data from my text file so it can calculate the pay of the employees.
So far it only reads one line.

Lane Holden 124578 m 45
Alex Peoples 854621 o 54
Gloria Roper 845791 t 61
Brice Diligant 984517 m 34
Victoria Wellen 213564 p 51
Oscar Sulard 652147 t 48
Samual Chaplin 231987 m 39
Brianna Niven 763452 t 51
Dani Kollin 892341 o 42
Alastair Palmatier 234876 m 38





#include<iostream> //Header File for console I/O
#include<iomanip>
#include <fstream>
#include<string>

using namespace std;

const double MIN_WAGE = 15;
const double NORM_HOURS = 40;
const double fed_tax = 0.15;
const double state_tax = 0.05;
const double soc_tax = 0.075;
const double med_tax = 0.015;


// begin min Function Definition
int main()
{
// ifstream inputFile;
ifstream myfile("payrolldata.txt", ios::in);
string employeeID, payrolldata, line;
double hoursWorked , totalPay , payRate ;
char payCode, again ;
float percentage, finalTotalPay ;

// Display Identtification on screen
cout << "Assignment 4" << endl;
cout << "Programmed by Rodger Coleman" << endl;


if (myfile.is_open());
{

getline(myfile, line);
cout << line << endl;
myfile.close();


getline(myfile, line);
cout << line << endl;
myfile.close();
}


do
{
cout << "Enter Employees" << endl;

// cin >> employeeID >> payCode >> hoursWorked;



switch (payCode){
case 'm':
case 'M': payRate = MIN_WAGE;
break;

case 'o': case 'O': payRate = MIN_WAGE + 3.00;
break;
case 't':
case 'T': payRate = MIN_WAGE + 6.00;
break;
case 'n':
case 'N':
default: cout << "you have entered the incorrect paycode" << endl;
break;

}
if (payRate) {
double totalPay (hoursWorked * payRate);
if (hoursWorked > NORM_HOURS)
totalPay += payRate * (hoursWorked - NORM_HOURS) * 1.5;
cout << setprecision(2) << fixed;
cout << "Pay rate: $ " << setw(2) << payRate << " Pay Amount: $ " << setw(2) << totalPay << '\n';
if (percentage = totalPay * fed_tax);
cout << "federal tax rate " << percentage << endl;
if (percentage = totalPay * state_tax);
cout << "State tax rate " << percentage << endl;
if (percentage = totalPay * soc_tax);
cout << "Social Security tax rate " << percentage << endl;
if (percentage = totalPay * med_tax);
cout << "Medicare tax rate " << percentage << endl;
if (finalTotalPay = totalPay - (totalPay * 0.15 + totalPay * 0.05 + totalPay * 0.075 + totalPay * 0.015) );
cout << "Total pay " << finalTotalPay << endl;

}





cout << "add another employee? (Y/N): ";
cin >> again;
} while ( again == 'Y' || again == 'y');


return 0;
}
PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

HINT: you can edit your post and add code tags.

Some formatting & indentation would not hurt either
Here is a start. The first and highest priority step with this problem is to read the file successfully and get some output. Titles and credits are the lowest priority. Formatting is next to that as a low priority.

Once you've got this sort of code to work the way you want it to you can then extract the relevant parts as (simple) functions and add the bells an whistles like adding/modifying and processing records.

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
#include<iostream> //Header File for console I/O
#include<iomanip>
#include <fstream>
#include<string>

using namespace std;

const double MIN_WAGE = 15;
const double NORM_HOURS = 40;
const double fed_tax = 0.15;
const double state_tax = 0.05;
const double soc_tax = 0.075;
const double med_tax = 0.015;


// begin min Function Definition
int main()
{
    // ifstream inputFile;
    ifstream myfile("payrolldata.txt", ios::in);
    
    string first_name, second_name;
    int ID{0};
    char pay_code{'?'};
    int hours_worked{0};
    double pay_rate{0};
    
    // Display Identtification on screen
    cout << "Assignment 4" << endl;
    cout << "Programmed by Rodger Coleman" << endl;
    
    if (myfile.is_open())
    {
        
        cout << "File opened successfully\n";
        
        while(myfile
              >> first_name >> second_name >> ID >> pay_code >> hours_worked )
        {
            switch (toupper(pay_code))
            {
                case 'M':
                    pay_rate = MIN_WAGE;
                    break;
                    
                case 'O':
                    pay_rate = MIN_WAGE + 3.00;
                    break;
                    
                case 'T':
                    pay_rate = MIN_WAGE + 6.00;
                    break;
                    
                case 'N':
                    cout << "What happens here?\n";
                    
                default: cout << "ERROR: you have entered an incorrect paycode" << endl;
                    break;
            }
            
            cout
            << "NAME: " << first_name << ' ' << second_name << ' '
            << "ID: " << ID << ' '
            << pay_code << ' '
            << pay_rate << ' ' << hours_worked << '\n';
            
            // BLAH, BLAH, BLAH ...
        }
    }
    else
    {
        cout << "File not opened\n";
        return -99;
    }
    
    return 0;
} 



Assignment 4
Programmed by Rodger Coleman
File opened successfully
NAME: Lane Holden ID: 124578 m 15 45
NAME: Alex Peoples ID: 854621 o 18 54
NAME: Gloria Roper ID: 845791 t 21 61
NAME: Brice Diligant ID: 984517 m 15 34
ERROR: you have entered an incorrect paycode
NAME: Victoria Wellen ID: 213564 p 15 51
NAME: Oscar Sulard ID: 652147 t 21 48
NAME: Samual Chaplin ID: 231987 m 15 39
NAME: Brianna Niven ID: 763452 t 21 51
NAME: Dani Kollin ID: 892341 o 18 42
NAME: Alastair Palmatier ID: 234876 m 15 38
Program ended with exit code: 0
PS getline() isn't needed because by the look of it there are only 2 names per entry. If the number of names varied then getline() would be useful.
So far it only reads one line.


That's because after you read the first line using getline(), you then close the file and hence subsequent file operations fail!
Also, if (myfile.is_open()); contains a blooper
I emphasize using code tags for the simple reason it makes reading, and commenting on, code MUCH easier.
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
#include<iostream> //Header File for console I/O
#include<iomanip>
#include <fstream>
#include<string>

using namespace std;

const double MIN_WAGE = 15;
const double NORM_HOURS = 40;
const double fed_tax = 0.15;
const double state_tax = 0.05;
const double soc_tax = 0.075;
const double med_tax = 0.015;


// begin min Function Definition
int main()
{
   // ifstream inputFile;
   ifstream myfile("payrolldata.txt", ios::in);
   string employeeID, payrolldata, line;
   double hoursWorked, totalPay, payRate;
   char payCode, again;
   float percentage, finalTotalPay;

   // Display Identtification on screen
   cout << "Assignment 4" << endl;
   cout << "Programmed by Rodger Coleman" << endl;


   if (myfile.is_open());
   {

      getline(myfile, line);
      cout << line << endl;
      myfile.close();


      getline(myfile, line);
      cout << line << endl;
      myfile.close();
   }


   do
   {
      cout << "Enter Employees" << endl;

      // cin >> employeeID >> payCode >> hoursWorked;



      switch (payCode)
      {
      case 'm':
      case 'M': payRate = MIN_WAGE;
         break;

      case 'o': case 'O': payRate = MIN_WAGE + 3.00;
         break;
      case 't':
      case 'T': payRate = MIN_WAGE + 6.00;
         break;
      case 'n':
      case 'N':
      default: cout << "you have entered the incorrect paycode" << endl;
         break;

      }
      if (payRate)
      {
         double totalPay(hoursWorked * payRate);
         if (hoursWorked > NORM_HOURS)
            totalPay += payRate * (hoursWorked - NORM_HOURS) * 1.5;
         cout << setprecision(2) << fixed;
         cout << "Pay rate: $ " << setw(2) << payRate << " Pay Amount: $ " << setw(2) << totalPay << '\n';
         if (percentage = totalPay * fed_tax);
         cout << "federal tax rate " << percentage << endl;
         if (percentage = totalPay * state_tax);
         cout << "State tax rate " << percentage << endl;
         if (percentage = totalPay * soc_tax);
         cout << "Social Security tax rate " << percentage << endl;
         if (percentage = totalPay * med_tax);
         cout << "Medicare tax rate " << percentage << endl;
         if (finalTotalPay = totalPay - (totalPay * 0.15 + totalPay * 0.05 + totalPay * 0.075 + totalPay * 0.015));
         cout << "Total pay " << finalTotalPay << endl;

      }





      cout << "add another employee? (Y/N): ";
      cin >> again;
   } while (again == 'Y' || again == 'y');


   return 0;
}

Lots of warnings from Visual Studio with your code.

You have "empty control statements" on numerous lines. You terminate your if statements with ; so any following block of code is ALWAYS run. Lines 31, 77, 79, 81, 83 & 85.

You use uninitialized variables, payCode, payRate & hoursWorked, so you potentially have garbage data.

totalPay instantiated on line 22 is unreferenced (not used) when you instantiate it again on line 72.

The biggest problem is reading data from your file. Because you prematurely terminate your "is the file open" check you are attempting to read data whether the file is open or not.

Plus, as pointed out by seeplus, you read a line at line 34 and then close the file. Your 2nd file read at line 39 now tries to read data from a closed file!

Your code will compile, but the warnings you should be seeing demonstrate there are problems. And one rather nasty issue with your file I/O.
BTW, thank you for including some data for the data file.

Here's a VERY brief rewrite of the file I/O so you can confirm your code does indeed open and read the file correctly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <string>

int main()
{
   std::ifstream myfile("payrolldata.txt", std::ios::in);

   std::string line;

   if (!myfile.is_open())
   {
      std::cerr << "** ERROR OPENING FILE! **\n";
      return 1; // terminate, can't continue
   }
   else
   {
      while (std::getline(myfile, line))
      {
         std::cout << line << '\n';
      }
      myfile.close();
   }
}
Lane Holden 124578 m 45
Alex Peoples 854621 o 54
Gloria Roper 845791 t 61
Brice Diligant 984517 m 34
Victoria Wellen 213564 p 51
Oscar Sulard 652147 t 48
Samual Chaplin 231987 m 39
Brianna Niven 763452 t 51
Dani Kollin 892341 o 42
Alastair Palmatier 234876 m 38

How you handle the properly read data is up to you. One method: store each line in a vector of strings that you can process each line into the needed parts.

Or parse each read line into containers to hold the individual data parts. std::vector is a variable sized container that can expand as you add data.

Using std::stringstream (requires C++17 or later) is helpful for parsing a string.
https://en.cppreference.com/w/cpp/header/sstream
Last edited on
I expanded my example code to parse each line of data into a struct, shoved the struct into a vector and then create a formatted table of employees using C++20's std::format:
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
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <format>

struct Employee
{
   std::string  first_name;
   std::string  last_name;
   unsigned int ID;
   char         gender;
   unsigned int age;
};

int main()
{
   std::ifstream myfile("payrolldata.txt", std::ios::in);

   std::string line;

   std::vector<Employee> employees;

   if (!myfile.is_open())
   {
      std::cerr << "** ERROR OPENING FILE! **\n";
      return 1; // terminate, can't continue
   }
   else
   {
      while (std::getline(myfile, line))
      {
         Employee employee;

         std::istringstream data(line);

         data >> employee.first_name;
         data >> employee.last_name;
         data >> employee.ID;
         data >> employee.gender;
         data >> employee.age;

         employees.push_back(employee);
      }
      myfile.close();
   }

   std::cout << "There are " << employees.size() << " employees.\n\n";

   std::string format { "{:>15}{:>15}{:>10}{:>10}{:>5}\n" };

   std::cout << std::format(format, "Last Name", "First Name", "ID", "Gender", "Age");

   for (const auto& itr : employees)
   {
      std::cout << std::format(format,
                               itr.last_name, itr.first_name,
                               itr.ID, itr.gender, itr.age);
   }
}
There are 10 employees.

      Last Name     First Name        ID    Gender  Age
         Holden           Lane    124578         m   45
        Peoples           Alex    854621         o   54
          Roper         Gloria    845791         t   61
       Diligant          Brice    984517         m   34
         Wellen       Victoria    213564         p   51
         Sulard          Oscar    652147         t   48
        Chaplin         Samual    231987         m   39
          Niven        Brianna    763452         t   51
         Kollin           Dani    892341         o   42
      Palmatier       Alastair    234876         m   38
Last edited on
What - 2 last names? Whow - a 4-type gender :) :)

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
// As C++20
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <format>

struct Employee {
	std::string    first_name;
	std::string    last_name;
	unsigned       ID {};
	char           code {};
	unsigned       hours {};
};

int main() {
	std::ifstream myfile("payrolldata.txt");

	if (!myfile)
		return (std::cerr << "** ERROR OPENING FILE! **\n"), 1;

	std::vector<Employee> employees;

	for (Employee emp; myfile >> emp.first_name >> emp.last_name >> emp.ID >> emp.code >> emp.hours; employees.emplace_back(std::move(emp)));

	std::cout << "There are " << employees.size() << " employees.\n\n";

	const auto format {"{:>15}{:>15}{:>10}{:>10}{:>8}\n"};

	std::cout << std::format(format, "Last Name", "First Name", "ID", "Code", "Hours");

	for (const auto& [first, last, id, code, hours] : employees)
		std::cout << std::format(format, last, first, id, code, hours);
}



There are 10 employees.

      Last Name     First Name        ID      Code   Hours
         Holden           Lane    124578         m      45
        Peoples           Alex    854621         o      54
          Roper         Gloria    845791         t      61
       Diligant          Brice    984517         m      34
         Wellen       Victoria    213564         p      51
         Sulard          Oscar    652147         t      48
        Chaplin         Samual    231987         m      39
          Niven        Brianna    763452         t      51
         Kollin           Dani    892341         o      42
      Palmatier       Alastair    234876         m      38


However I don't think there's anything in the requirement to need to store the file contents in a container.
Last edited on
I corrected that little typo, but you caught me, seeplus. Oooops!

I kept staring at the code and the output and only a few minutes ago noticed my mistake.

Yeah, I should have default initialized the non-string struct members, VS whinged quite petulantly when I didn't.

Oooooh! I had forgotten about using structured binding. That for loop use is much less cumbersome than what I had.

Still nice to show different ways to do it. :)
Last edited on
Perhaps:

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
// As C++20
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <format>

using namespace std::string_literals;

constexpr double MIN_WAGE {15};
constexpr double NORM_HOURS {40};
constexpr double fed_tax {0.15};
constexpr double state_tax {0.05};
constexpr double soc_tax {0.075};
constexpr double med_tax {0.015};

struct Employee {
	std::string	first_name;
	std::string	last_name;
	unsigned	ID {};
	char        code {};
	unsigned	hours {};
};

double process(const Employee& emp) {
	double payRate {};

	switch (emp.code) {
		case 'm':
		case 'M':
			payRate = MIN_WAGE;
			break;

		case 'o':
		case 'O':
			payRate = MIN_WAGE + 3.00;
			break;

		case 't':
		case 'T':
			payRate = MIN_WAGE + 6.00;
			break;

		case 'n':
		case 'N':
		default:
			return 0;
	}

	const auto totalPay {emp.hours * payRate + (emp.hours > NORM_HOURS ? payRate * (emp.hours - NORM_HOURS) * 1.5 : 0)};
	const auto fedtax {totalPay * fed_tax};
	const auto statetax {totalPay * state_tax};
	const auto ssectax {totalPay * soc_tax};
	const auto medi {totalPay * med_tax};

	return totalPay - fedtax - statetax - ssectax - medi;
}

int main() {
	std::ifstream myfile("payrolldata.txt");

	if (!myfile)
		return (std::cerr << "** ERROR OPENING FILE! **\n"), 1;

	const auto format {"{:>15}{:>15}{:>10}{:>10}{:>8}"s};

	std::cout << std::format(format + "{:>10}\n", "Last Name", "First Name", "ID", "Code", "Hours", "Pay");

	for (Employee emp; myfile >> emp.first_name >> emp.last_name >> emp.ID >> emp.code >> emp.hours;)
		if (const auto pay {process(emp)}; pay)
			std::cout << std::format(format + "{:10.2f}\n", emp.last_name, emp.first_name, emp.ID, emp.code, emp.hours, pay);
		else
			std::cout << "Invalid data\n";
}



      Last Name     First Name        ID      Code   Hours       Pay
         Holden           Lane    124578         m      45    559.12
        Peoples           Alex    854621         o      54    958.50
          Roper         Gloria    845791         t      61   1379.17
       Diligant          Brice    984517         m      34    362.10
Invalid data
         Sulard          Oscar    652147         t      48    894.60
        Chaplin         Samual    231987         m      39    415.35
          Niven        Brianna    763452         t      51   1006.42
         Kollin           Dani    892341         o      42    575.10
      Palmatier       Alastair    234876         m      38    404.70

Topic archived. No new replies allowed.