I am getting a problem while using
cin >> PayRate
and
cin >> H_worked
what could be the problem? Even the compiler doesn't show any errors but when program runs the 2nd and 3rd cin values aren't read by compiler.
Program:
#include <iostream.h>
#include<conio.h>
int main()
{
int employeeName, H_worked;
float PayRate, GrossPay, NetPay;
cout << "Please input your employee's name:";
cin >> employeeName;
cout << "Input hourly wage rate:";
cin >> PayRate;
cout << endl;
cout << "Input hours worked :";
cin >> H_worked;
cout << endl;
if (H_worked > 40)
{
H_worked = H_worked*1.5;
GrossPay = H_worked*PayRate;
cout << "Your employees gross pay for this week is" << GrossPay << endl;
NetPay = GrossPay - (GrossPay* 3.625);
cout << "Your employees net pay is" << NetPay << endl;
}
else (H_worked <= 40);
{
GrossPay = H_worked*PayRate;
cout << "Your employees gross pay for this week is" << GrossPay << endl;
NetPay = GrossPay - (GrossPay*3.625);
cout << "And your employees net pay is" << NetPay << endl;
}
return 0;
getch();
}
You declared employeeName as an int but that does not make any sense as names have letters not numbers. If you are actually entering in character data then this will cause cin to fail and that will make any subsequent call fail as well. This fits with your description of what is happening. To fix this first we need to make employeeName a std::string so we can store letters.
int employeeName, H_worked;
//becomes
std::string employeeName;
int H_worked;
Then we need to change the input method. Since a name can have spaces in it we need to use std::getline instead of >> to get the name as >> will stop when it sees a space.
cout << "Please input your employee's name:";
std::getline(std::cin, employeeName);
You also have a semicolon at the end of your else condition
else (H_worked <= 40);
This means that
{
GrossPay = H_worked*PayRate;
cout << "Your employees gross pay for this week is" << GrossPay << endl;
NetPay = GrossPay - (GrossPay*3.625);
cout << "And your employees net pay is" << NetPay << endl;
}
Will always run as ; ends the else part.
Then we have the issue that you are using non standard includes. In standard c++
#include <iostream.h>
Should be
#include <iostream>
As all standard includes omit the .h. Since all of the standard components live in the std namespace you are also going to have to deal with that. You can either put std:: in front of all the std components or you can put using std::cout;, using std::cin, ect. I would not suggest using using namespace std; for the reasons outlined in Why is “using namespace std;” considered bad practice?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using orwell dev| c++
C++ is a new language to, i am coming from c# which is like i would say 70% the same.
here is my code
#include<iostream>
#include<fstream>
using namespace std;
///loading libraries
float const taxnet = .9;
float const taxwh = .1;
int employeenumber;
float payrate, gross, net, manhours, overtime, taxes;
///declaring variablies and costants
char more;
char more2;
///user controls
///payroll calculations function
void payrollcalc () {
if (manhours>40) {
overtime= manhours-40;
gross= ((manhours - overtime) * payrate)+((payrate * 1.5)* overtime);
//overtime claculation
}
else {
gross =manhours * payrate;
//no overtime calculation
}
taxes= gross * taxwh;
net = gross * taxnet;
//taxesand net pay calculation
cout<< " Your ID is " << employeenumber <<endl;
cout<< " # of hours worked " << manhours << endl;
cout<< " Your Hourly rate is " << payrate << endl;
cout<< " Your Gross pay is " << gross << endl;
cout<< " Your tax rate is " << taxwh << endl;
cout<< " Amount of taxes " << taxes << endl;
cout<< " Your net pay is " << net << endl;
///writing to file
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open (empnum+".txt");
payroll<< " Your ID is " << employeenumber <<endl;
payroll<< " # of hours worked " << manhours << endl;
payroll<< " Your Hourly rate is " << payrate << endl;
payroll<< " Your Gross pay is " << gross << endl;
payroll<< " Your tax rate is " << taxwh << endl;
payroll<< " Amount of taxes " << taxes << endl;
payroll<< " Your net pay is " << net << endl;
payroll.close();
}
main(){
while (more != 27){
//main
cout<< "Hit 1 to enter data hit 2 to recall dat hit esc to exit";
///instructions
newdata:
///call back see line 115
if (more == 49) {
cout<< "Enter Employee ID:";
cin>> employeenumber;
cout<<"Enter Number of Hours Worked:";
cin>> manhours;
cout<<"Enter Pay rate:";
cin>> payrate;
cin>> payrollcalc;
}
else (more == 50) {
olddata:
///call back see line 111
errorreset:
cout<< "Enter employee number";
cin>> employeenumber;
///reading in data
ifstream payroll = employeenumber;
payroll.open(employeenumber".txt");
if (!payroll){
cout>> "Check employeenumber and try agian" endl;
goto errorreset:
///error check
}
cout>> payroll.eof endl;
cout>> endl;
cout>> endl;
cout>> "Press Enter to see another employee number; Press space to enter new employee information; press escape to exit the program" endl;
if (more2 == 13 ){
goto olddata;
}
else (more2 == 32){
goto newdata;
}
///sending back to the loop
}
//entering data
return 0;
}
}
I think my issues is in this segment
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open (empnum+".txt");
payroll<< " Your ID is " << employeenumber <<endl;
payroll<< " # of hours worked " << manhours << endl;
payroll<< " Your Hourly rate is " << payrate << endl;
payroll<< " Your Gross pay is " << gross << endl;
payroll<< " Your tax rate is " << taxwh << endl;
payroll<< " Amount of taxes " << taxes << endl;
payroll<< " Your net pay is " << net << endl;
payroll.close();
If some can step me through where i am going off the rails i would be grateful because i am out of ideas.
First off consider turning up the error/waring level of your compiler, for gcc/clang a sensible level would be -Wall -Wextra for a start.
Let me go through some of the problems I see in your code.
main(){
We got a first problem here already. The only 2 signatures allowed for the main function in C++ are int main() or int main(int argc, char *argv[]). Yours might be accepted due to legacy reasons (implicit return type of int in C if you don't specify any) but shouldn't be used.
cout>> payroll.eof endl; // this line absolutely makes no sens and you forgot some `<<` in here probably.
cout>> endl;
cout>> endl;
cout>> "Press Enter to see another employee number; Press space to enter new employee information; press escape to exit the program" endl;
The 'arrows' point into the wrong direction. It should be cout << endl. To remember it see them as arrows that signify the data flow. cin >> variable the data is read from cin and gets put into the variable, cout << variable the variable gets output into cout.
Then you got a read that doesn't make sense:
cin>> payrollcalc;
payrollcalc is a function, I don't know what you wanted to do here, but you should probably call it like payrollcalc();, trying to read from cin into it doesn't make sense.
You're also using std::string without #include <string>. Also note that you should probably put a space in the include line like I did. I don't know if it's a problem without space of the top of my head but it's certainly more readable with a space.
Now for some bad practices and other stuff that I should probably point out. Your indentation and formatting were very messy and made it hard to spot anything you should probably see into cleaning it up a bit.
As for goto it's considered bad practice/harmful. This was started by Dijkstra. Now to say it got it's uses still in some places and is often over exaggerated but for the simple code you're using I don't think it's necessary and could probably be done in a better more structured way that makes the logic easier to understand, remember code is read far more often than you write it and readability is very important. If you're curious about the problems, #itsnotmyrealname posted a link on your question already for you to look through.
Also you got inconsistencies that make it harder to read/confusing.
gross =manhours * payrate; // inconsistent assignments
taxes= gross * taxwh;
net = gross * taxnet;
std::to_string(employeenumber) // inconsistent function calls.
payroll.open (empnum+".txt");
As for the global variables if you've already got some experience in programming (in C# like you said) then you probably know that they are considered bad practice too and should be avoided, you should look into making them local variables and passing them around as function arguments/returning them from functions.
I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)
Hoping someone can help. I'm able to compile with no error, I'm not finding any syntax errors but when I run this, it crashes. Debug segfaults on launch. Full disclosure, this is homework. I'm not asking for someone to code this, just look at my problem and my existing code and maybe point me toward what I did that broke this so badly?
Question: You found an exciting summer job for five weeks. It pays, say, $15.50 per hour. Suppose that the total tax you pay on your summer job income is 14%. After paying the taxes you spend 10 % of your net income to buy new clothes and other accessories for the next school year and 1% to buy school supplies. After buying clothes and school supplies, you use 25% of the remaining money to buy savings bonds. For each dollar you spend to buy savings bonds, your parents spend $0.50 to buy additional savings bonds for you. Write a program that prompts the user to enter the pay rate for an hour and the number of hours you worked each week. The program then outputs the following:
a. Your income before and after taxes from your summer job.
b. The money you spend on clothes and other accessories.
c. The money you spend on school supplies.
d. The money you spend to buy savings bonds.
e. The money your parents spend to buy additional savings bonds for you.
Code:
// Libraries defined
#include <iomanip>
#include <iostream>
using namespace std;
//Main function
int main ()
{
//Input variables
double hourlyrate;
double hweek1;
double hweek2;
double hweek3;
double hweek4;
double hweek5;
//Output variables
double beforetax;
double netincome;
double clothmoney;
double suppliesmoney;
double moneyonbonds;
double additionalbonds;
double remain;
//This statement takes care of the decimal places
cout << fixed << showpoint << setprecision(2);
//Input from user
cout << "Enter your hourly rate: " << hourlyrate;
cin >> hourlyrate;
cout << "Week 1: " << hweek1;
cin >> hweek1;
cout << "Week 2: " << hweek2;
cin >> hweek2;
cout << "Week 3: " << hweek3;
cin >> hweek3;
cout << "Week 4: " << hweek4;
cin >> hweek4;
cout << "Week 5: " << hweek5;
cin >> hweek5;
//Mathematics
beforetax = hourlyrate * (hweek1 + hweek2 + hweek3 + hweek4+
hweek5) ;
netincome = beforetax - beforetax * 0.14;
clothmoney = netincome * 0.1;
suppliesmoney = netincome * 0.01;
remain = netincome - clothmoney - suppliesmoney;
moneyonbonds = remain * 0.25;
additionalbonds = static_cast<double>(moneyonbonds) * .50;
//Output to user
cout << endl << "Income before tax = $" << beforetax << endl
<< "Net income = $" << netincome << endl << "Money for clothes/accesories = $"
<< clothmoney << endl << "Money for supplies = $"<< suppliesmoney << endl
<< "Money for saving bonds = $" << moneyonbonds << endl
<< "Additional saving bonds money = $" << additionalbonds;
return 0;
}
I received this error
cout << "Enter your hourly rate: " << hourlyrate;
You try to output the variable before you initialize it.
This is probably unintentional.
The next line is
cin >> hourlyrate
It is the same for every variable. You should initialize them or not output them.
Are you sure about this:
cout << "Enter your hourly rate: " << hourlyrate;
cin >> hourlyrate;
cout << "Week 1: " << hweek1;
cin >> hweek1;
cout << "Week 2: " << hweek2;
cin >> hweek2;
cout << "Week 3: " << hweek3;
cin >> hweek3;
cout << "Week 4: " << hweek4;
cin >> hweek4;
cout << "Week 5: " << hweek5;
cin >> hweek5;
I think that you wanted:
cout << "Enter your hourly rate: ";
cin >> hourlyrate;
instead of:
cout << "Enter your hourly rate: "<< hourlyrate;
cin >> hourlyrate;
This is a program that I have been working on. I am just starting out in programming, so I am just trying to write simple programs for now. The ones I have done have worked great till this one. The program will run but it doesn't let the user enter all the information. I am not sure why. If someone could please help me understand. Here is the code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double salary = 0.0;
double wages = 0.0;
float employee = 0;
int hours;
double total = 0.0;
cout << "Please enter an employee name or -1 to quit";
cin >> employee;
cout << "Please enter the employee wages: $" << endl;
cin >> wages;
cout << "Please enter how many hours the employee worked" << endl;
cin >> hours;
wages * hours == salary;
cout << "The employee total earnings is $" << total << endl;
cout << "Please enter an employee name or -1 to quit";
system("pause");
return 0;
}
Thanks again for your time and help.
Here are the changes I have made but it's still not running right.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double salary = 0.0;
double wages = 0.0;
float employee = 0;
int hours;
double total = 0.0;
cout << "Please enter an employee name or -1 to quit";
cin >> employee;
cout << "Please enter the employee wages: $" << endl;
cin >> wages;
cout << "Please enter how many hours the employee worked" << endl;
cin >> hours;
salary = wages * hours;
cout << "The employee total earnings is $" << total << endl;
cout << "Please enter an employee name or -1 to quit";
cin >> employee;
system("pause");
return 0;
}
You have employee set as a float. I'm assuming that you mean an employee name, so you want to have a string there.
The simple explanation is that cin breaks when it's expecting a number and you give it a string. And by "breaks" I mean that subsequent cins, especially ones that expect numbers, get swallowed up in a blur of nonsense.
The line
wages * hours == salary;
is meaningless (i'm not even exactly sure what it does). You probably wanted to calculate the salary, but that should be something like
salary = wages * hours;
You also never calculate your total variable - it's always 0.
cout << "Please enter an employee name or -1 to quit";
system("pause");
return 0;
Is your problem here? Because you aren't asking for input here, which could be the reason.
It depends on what you mean by "All the information." My guess is that you're trying to enter a first and last name for the employee name, and it's skipping some inputs. The reason for this is that cin (somewhat unintuitively) splits input up by whitespace. That means that it treats each string, number, lump of characters, etc (referred to as "tokens") as a separate cin object, even if you enter more than one and press enter.
So, if you see this:
Please enter an employee name or -1 to quit
and enter "John Doe," it will store "John" to employee, print "Please enter the employee wages: $," and then immediately store "Doe" to wages, without prompting for input, because "Doe" is still waiting to be stored This is one of the first C++ "gotcha!"s that beginners experience, and there are many ways around it. One of them is to use cin.getline(...). Another is to use cin >> noskipws >> employee;.
http://www.cplusplus.com/reference/iostream/manipulators/noskipws/
http://www.cplusplus.com/reference/iostream/istream/getline/
Obviously, storing a word to a float has issues of its own, but I assume you're handling that separately. If you want to store a string, look into std::string.
You need a loop. One that runs until the employee name is equal to "-1".
I'm not sure what you want to achieve, but maybe you want something like this:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double salary = 0.0;
double wages = 0.0;
String employee = "";
int hours = 0;
double total = 0.0;
cout << "Please enter an employee name or -1 to quit";
cin >> employee;
cout << "Please enter the employee wages: $" << endl;
cin >> wages;
cout << "Please enter how many hours the employee worked" << endl;
cin >> hours;
salary = wages * hours;
cout << "The employee total earnings is $" << total << endl;
cout << "Please enter an employee name or -1 to quit";
system("pause");
return 0;
}
If you want validation on the employee name, you need while loop on the input employe untill the user insert some token.
I have to make a loop to gather all the information from the users input of the employees. As you can see, I have gotten the parts where I ask the user how many employees and what their information is. Now all I have to is print that information to the screen like this, just without the periods between each and with a few spaces between each :
Weekly Payroll:
Name...............Title........Gross.......Tax.........Net
----------------------------------------
Ebenezer Scrooge.....................Partner...250.00......62.25.....187.75
Bob Cratchit...............................Clerk.......15.00........2.00.......13.00
And this is what I have :
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT
{
char name[MAXSIZE];
char title;
double SSNum;
double Salary;
double Withholding_Exemptions;
};
EmployeeT employees[MAXSIZE];
int main()
{
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE)
{
cout << "Error: Maximum number of employees is 20\n" ;
cout << "How many Employees? ";
cin >> numberOfEmployees;
}
char name[MAXSIZE];
int title;
double SSNum;
double Salary;
double Withholding_Exemptions;
for (int count=0; count < numberOfEmployees; count++)
{
cout << "Name: ";
cin >> employees[ count ].name;
cout << "Title: ";
cin >> employees[ count ].title;
cout << "SSNum: \n";
cin >> employees[ count ].SSNum;
cout << "Salary: \n";
cin >> employees[ count ].Salary;
cout << "Withholding Exemptions: \n";
cin >> employees[ count ].Withholding_Exemptions;
}
double gross;
double tax;
double net;
double adjusted_income;
gross = employees[ count ].Salary;
adjusted_income = employees[ count ].Salary - 1.00;
tax = adjusted_income * .25;
net = gross - tax;
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for (int count=0; count < numberOfEmployees; count++)
{
cout << employees[count].name << " \t" << employees[count].title << " \t" <<
gross << "\t" << tax << "\t" << net << "\n";
}
system("pause");
}
Ok I updated the program. Now I'm trying to do the calculations. This what I'm doing...
To calculate payroll:
Gross pay is the weekly salary which was previously entered for the employee.
Net pay is calculated as the gross pay minus the amount of tax.
To calculate tax: Deduct $1 from the salary for each withholding exemption. This is the adjusted income. If the adjusted income is less than 0, then use 0 as the adjusted income.
Multiply the adjusted income by the tax rate, which you should assume is a flat 25%.
As an example, if Bob Cratchit has a weekly income of $15 and 7 dependents, then his adjusted income would be $8. His tax would be 25% of $8 which is $2, and therefore his net pay is $13.
I have started trying to get this. I put it between the second loop and the last loop. Is this right?
A small example for printing columns using C++ streams:
#include <iomanip>
#include <ios>
std::ostream& operator<<(std::ostream& a_out, const EmployeeT& a_e)
{
a_out << std::setfill(' ')
<< std::left
<< std::setw(sizeof(a_e.name))
<< a_e.name
<< std::setw(0)
<< a_e.title
<< " "
<< std::setw(10)
<< a_e.SSNum
<< a_e.Salary
<< a_e.Withholding_Exemptions;
return a_out;
}
This would allow you to write an employee to standard output using:
std::cout << employees[n] << "\n";
Use a similar approach for the column headings.
Other points:
Prefer std::string to char[] (or char*) then you don't have to limit the length of the string (or explicitly manage the memory)
Use std::vector instead of a fixed array to avoid a limit
Make use of STL algorithms (std::for_each, std::copy for example) for performing operations on elements in containers (or array)
you can use the same loop for insertion and displaying or anything!! because it traverses through the whole loop.
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for (int count=0; count < numberOfEmployees; count++)
{
cout << employees[count].name << " \t" << employees[count].title << " \t" <<
Gross << "\t" << tax << "\t" << Net << "\n";
}
Find net,tax and gross of each structure object and print.
Check if you want name as int at the marked position.
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT {
char name[MAXSIZE];
char title;
double SSNum;
double Salary;
double Withholding_Exemptions;
};
EmployeeT employees[MAXSIZE];
int main() {
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE) {
cout << "Error: Maximum number of employees is 20\n" <<
"How many Employees? ";
cin >> numberOfEmployees;
}
int name; // name is char[] or string
int title;
double SSNum;
double Salary;
double Withholding_Exemptions;
for (int count = 0; count < numberOfEmployees; count++) {
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "SSNum: \n";
cin >> employees[ count ].SSNum;
cout << "Salary: \n";
cin >> employees[ count ].Salary;
cout << "Withholding Exemptions: ";
cin >> employees[ count ].Withholding_Exemptions;
}
}
You can use the '\t' sequence, which represent in C++ a "Tab space" (like when you press Tab on your Keyboard).
As for the loop, it should be something like:
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for(int n=0; n < employees; n++)
{
cout << employees[n].name << " \t" << employees[n].title << " \t" ...... << "\n";
}
It should work :)
You could look into the STL iomanip header functions, like setw()
Formatting Cout Output in C++ using iomanip
. With that it should be possible to get decent fix sized columns, which tabs likely wont.
Your code has seems OK, although it is more complicated than it should be, and the input-loop has no error-handling (if a user enters something invalid, your program will stop working).
Here are some general pointers that can help you make your program better:
Use std::vector<EmployeeT> instead of an array - this way you don't have to limit the number of employees you can handle, because the vector can grow dynamically.
Provide an operator<<-overload for EmployeeT.
Look into Iostream-manipulators, particularly std::setw; This question is similar to your problem, and one solution uses manipulators to format the output.