How do I fix my while Error? - c++

I'm writing a program in Microsoft Visual Studio with C++ that will retrieve information from a .txt file. In that file there are negative numbers, but when I try to write a while loop that states what to do if there is a negative number, I get several errors.
Can someone please help me with this? Here is my code and I do realize there are errors but I can't figure out how to write the While loop statement to read these values which are hours worked and the hourly rate from the .txt file
Sample text file:
45.0 10.50
-35.0 7.75
50.0 12.00
45.0 -8.50
30.0 6.50
48.0 -10.25
-50.0 10.00
50.0 8.75
40.0 12.75
56.0 8.50
Code:
//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file
// that was created and called employee.txt.
// Input: Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay
// Typed by:
// Date:
//******************************
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);
const float hours = 40; // Regular 40 hour work week
const float ovTime = 1.5; // Overtime if hours go over 40
const float exemption = 200.0; // Exemption if pay goes over 200
const float fedTaxRate = 0.10; // Federal Tax Rate
const float stTaxRate = 0.03; // State Tax rate
ifstream inFile;
ofstream outFile;
int main()
{
inFile.open("employee.txt");
outFile.open("result.txt");
float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
inFile >> hours >> rate;
while(inFile)
{
if {
(hours <= 0)&& (rate <= 0);
outFile << "Invalid Data";
}
else{
return 0;
}
}
grossPay = computeGross(hours, rate);
computeTaxes (grossPay, taxableIncome, fedTax, stTax);
computeNetPay (grossPay, fedTax, stTax, NetPay);
outFile << fixed << showpoint << setprecision(2);
outFile << "Hours worked = " << hours << endl
<< "Hourly rate = " << rate << endl
<< "Employee's gross pay = " << grossPay << endl
<< "Taxable Income = " << taxableIncome << endl
<< "Federal Taxes = " << fedTax << endl
<< "State Taxes = " << stTax << endl
<< "Net Pay = " << NetPay << endl;
return 0;
}
float computeGross (float h, float r) //Computes for the Gross Pay
{
if (h > hours)
return hours * r + (h - hours) * r * ovTime;
else
return h * r;
}
void computeTaxes(float g, float& taxable, float& fedTax, float& stTax) //Computes both Taxes
{
taxable = g - exemption;
if (taxable > 0.0)
{
fedTax = fedTaxRate * taxable;
stTax = stTaxRate * taxable;
}
else
{
fedTax = 0.0;
stTax = 0.0;
}
}
float computeNetPay (float& grossPay, float& fedTax, float& stTax, float& NetPay)
{
return NetPay = grossPay - fedTax - stTax;
}

In your main function you have:
while(inFile)
{
if ((hours <= 0) && (rate <= 0))
{
outFile << "Invalid Data";
}
else {
return 0;
}
}
When the else is triggered the program finishes, the main function returns. You might want a continue break or nothing here instead, that return statement ends the main function not the While loop.
To get all the data out of the file your read statement ( inFile >> hours >> rate);
will need to be in this or another loop. Say after the IF test for validity, it could be in the Else.
while(inFile)
{
if ((hours <= 0) && (rate <= 0)) {
outFile << "Invalid Data";
}
else {
// call the data functions
// save the returned values
}
//prime hours and rate for the next loop
inFile >> hours >> rate;
}

Well.. my guess is this is what your looking for:
Note that the:
if ((hours <= 0) && (rate <= 0))
is changed to:
if ((hours <= 0) || (rate <= 0))
otherwise it won't ever hit the "invalid data" with your supplied data
//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file
// that was created and called employee.txt.
// Input: Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay
// Typed by:
// Date:
//******************************
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);
const float hours = 40; // Regular 40 hour work week
const float ovTime = 1.5; // Overtime if hours go over 40
const float exemption = 200.0; // Exemption if pay goes over 200
const float fedTaxRate = 0.10; // Federal Tax Rate
const float stTaxRate = 0.03; // State Tax rate
int main()
{
ifstream inFile ("employee.txt");
ofstream outFile ("result.txt");
float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
if (inFile.is_open())
{
while (! inFile.eof() )
{
inFile >> hours;
inFile >> rate;
if ((hours <= 0) || (rate <= 0))
{
outFile << "Invalid Data";
}
else
{
grossPay = computeGross(hours, rate);
computeTaxes (grossPay, taxableIncome, fedTax, stTax);
computeNetPay (grossPay, fedTax, stTax, NetPay);
outFile << fixed << showpoint << setprecision(2);
outFile << "Hours worked = " << hours << endl
<< "Hourly rate = " << rate << endl
<< "Employee's gross pay = " << grossPay << endl
<< "Taxable Income = " << taxableIncome << endl
<< "Federal Taxes = " << fedTax << endl
<< "State Taxes = " << stTax << endl
<< "Net Pay = " << NetPay << endl;
}
}
}
return 0;
}
The rest is the same

For a start, I think that this:
if {
(hours <= 0)&& (rate <= 0);
outFile << "Invalid Data";
}
Should be this:
if ((hours <= 0) && (rate <= 0)) {
outFile << "Invalid Data";
}
Note that to get code to format properly on StackOverflow, you should only use spaces, not tabs. I think that's whats causing your format issues.

Related

Don't understand why output is incorrect

I'm currently doing a Zybooks lesson for my C++ class and we're going over while loops. In this question, it wants me to calculate how many years it takes for a bank account to double it's initial balance. There is also an annual contribution added. My code is as follows:
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest + contribution;
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
I used this as an answer but was met with this unexpected result:
Output differs. See highlights below.
Input
100
Your output
Annual contribution:
Year: 13
Balance: 20627.8
Expected output
Annual contribution:
Year: 13
Balance: 20527.8
I see the expected output and your output differs by a 100, i.e. your contribution. Maybe the evaluation system doesn't add annual contribution once your target is reached. The below code gets your required output, but I think your code should have been the correct answer.
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
The problem is that you're making a contribution after the 13th year even though the target has been reached.
I would restructure to something like this, in order to only check the condition once:
while (true)
{
year++;
double interest = balance * RATE / 100;
balance += interest;
if (balance >= TARGET)
{
break;
}
balance += contribution;
}
This is because the last time the loop is being executed (at year=13), balance is less than TARGET but, after adding a contribution and interest into it, it jumps out of the loop with contribution and interest added to it.
So, the solution can be to use an if statement within the while loop to check if it exceeds the TARGET; if it does, then don't add contribution into it.
Replace your while loop with the following:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}

[C++} Not sure if this is even possible

I'm trying to find the average net pay for a payroll program. What I'm wondering is it possible to create an array from the outputted tabular data and use the array to calculate the average? Or do I have to do this a different way? My code thus far:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class employee {
ifstream fin;
char employeeid[12];
char employeename[20];
char martialstatus;
int hoursworked, overtime;
double hourlyrate, overtimepay, regularpay, grosspay, taxrate, taxamount, netpay, average;
void calculateGrosspay();
void calculateTax();
void calculateNetpay();
void printHeadings();
void printData();
double findAverage();
void printAverage();
public: employee();
~employee();
void printReport(); };
employee::employee(){
fin.open(payrollData.txt);
}; //Constructor
employee::~employee() {
fin.close(); } //Destructor
void employee::calculateGrosspay() {
if (hoursworked > 40) {
overtime = hoursworked - 40;
regularpay = hoursworked * hourlyrate;
overtimepay = overtime * (hourlyrate * 1.5);
grosspay = regularpay + overtimepay;
}
else grosspay = hoursworked * hourlyrate;
} //Calculate gross pay function
void employee::calculateTax() {
taxrate = .30;
taxamount = grosspay*taxrate;
} // calculate tax function
void employee::calculateNetpay() {
netpay = grosspay - taxamount;
} //Calculate net pay
void employee::printHeadings() {
cout << setw(45) << "-Employee Payroll Report-" << endl;
cout << "____________________________________________________________" << endl;
cout << "NAME ID HW OT RT-PAY OT-PAY Gross Tax NetPay" << endl;
cout << "____________________________________________________________" << endl;
} // print table headings
void employee::printData() {
cout << setprecision(2) << setiosflags(ios::fixed | ios::showpoint);
cout << setw(6) << employeename << setw(12) << employeeid << setw(4) << hoursworked << setw(3) << overtime << setw(8) << regularpay << setw(8)
<< overtimepay << setw(8) << grosspay << setw(8) << taxamount << setw(8) << netpay << endl;
} // print data
void employee::printReport() {
int i = 0;
printHeadings();
while (fin >> employeename >> employeeid >> hoursworked >> hourlyrate) {
calculateGrosspay();
calculateTax();
calculateNetpay();
printData();
i++;
}
}
double employee::findAverage() {
return average;
}
void printAverage() {
cout << endl;
cout << "The average netpay is" << average << endl;
}
void main() {
employee.printReport();
employee.findAverage();
employee.printAverage();
}
So after the program has printed the data to the console I want to find the average of the net pays and print it to the console. Best way to do this?
You'll probably need a vector like Soren mentioned. If you're trying to get some averages for all employees (which that's what I assume you're trying to do), then let's say we're going to try and get an average for gross pay.
You'll need a vector global, like such:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
vector<double> netPayList;
double globalAverage;
You'll then need to add information to the vector when GrossPay is calculated as such:
void employee::calculateNetpay()
{
netpay = grosspay - taxamount;
netPayList.push_back(netpay);
}
Finally, we can calculate the average in employee::findAverage(), we should also probably use a for loop for this as well, and in my opinion we should ditch the public function of "employee" and switch that over to a traditional function, since we are trying to get the average for many "employee" instances. The average calculation will now look like this:
double findAverage()
{
for (int iterator = 0; iterator < netPayList.size(); iterator++)
{
average += netPayList[iterator];
}
globalAverage /= netPayList.size();
return globalAverage;
}
Anyway, that's basically the gist of it. Keep working on your stuff, but also I would suggest that you title your questions better. Someone with more gumption and SO privileges than I will most likely edit your OP.

C++ Why is this outputting the wrong compound interest?

I've been trying to figure this out for sometime and I think it has something to do with the values I'm using for the calculations. I'm not exactly familiar with compound interest so I'm not sure were I'm going wrong. Any help would be appreciated.
#include <iostream>
#include <cmath>
using namespace std;
double interest_credit_card(double initial_balance, double interest_rate, int payment_months);
// Calculates interest on a credit card account according to initial balance,
//interest rate, and number of payment months.
int main ()
{
double initial_balance, interest_rate;
int payment_months;
char answer;
do
{
cout << "Enter your initial balace: \n";
cin >> initial_balance;
cout << "For how many months will you be making payments?\n";
cin >> payment_months;
cout << "What is your interest rate (as a percent)?: %\n";
cin >> interest_rate;
cout << endl;
cout << "You will be paying: $ " << interest_credit_card( initial_balance, interest_rate, payment_months) << endl;
cout << "Would you like to try again? (Y/N)\n";
cin >> answer;
}while (answer == 'Y' || answer == 'y');
cout << "Good-Bye.\n";
return 0;
}
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double compound_interest, compounding, compounding2, compounding3, compounding4;
while(payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate/100.0);
compounding = (interest_rate /12);
compounding2 = compounding + 1;
compounding3 = interest_rate * (payment_months/12);
compounding4 = pow(compounding2, compounding3);
compound_interest = initial_balance * compounding4;
initial_balance = initial_balance + compound_interest;
payment_months--;
}
return initial_balance;
}
Inputs and expected outputs:
Enter your initial balance: 1000
For how many months will you be making payments?: 7
What is your interest rate (as a percent)?: 9
You will be paying: $1053.70
It looks like you were trying a bunch of things and then left them in. The first solution you tried was almost right, you just forgot "/12":
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
while (payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate / 100.0/12);
payment_months--;
}
return initial_balance;
}
With a little better style:
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double total_payment = initial_balance;
double monthly_rate = interest_rate / 100.0 / 12;
for (int month = 1; month <= payment_months; ++month)
total_payment += total_payment * monthly_rate;
return total_payment;
}

My code is returning two really weird errors

My code isn't working. I don't know why. The errors I am getting don't make sense.
17 18 C:\Users\the beast\Desktop\Case study phase 3.0.6.cpp [Error] a function-definition is not allowed here before '{' token
I dont even know why it throwing this error.
77 1 C:\Users\the beast\Desktop\Case study phase 3.0.6.cpp [Error] expected '}' at end of input
^ all brackets are present checked no idea why it is throwing this error
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
using namespace std;
//loading libraries
float const taxnet = .9;
float const taxwh = .1;
float employeenumber;
float payrate=0;
float gross=0;
float net=0;
float manhours=0;
float overtime=0;
float taxes=0;
char usercontrols;
void data_loop(char usercontrols);
void writeWorkerInfo(ofstream &stream, float employeenumber, float manhours, float payrate, float gross, float taxes, float net);
void payrollcalc(float employeenumber, float manhours, float payrate, float gross, float taxes, float net);
void data_entry(float employeenumber, float manhours, float payrate);
void data_recall(float employeenumber);
void data_error_check(char usercontrols);
int main(){
// varibles
cout << "Hit 1 to enter new data; hit 2 load a file; hit escpae to exit." << endl;
cin >> usercontrols;
while (usercontrols != 27){
data_error_check(usercontrols);
}
return 0;
}
void data_error_check(char usercontrols){
cin >> usercontrols;
if(usercontrols == 49 || 50){
data_loop(usercontrols);
}
else if (usercontrols != 49 ||50){
cout << "Wrong button hit enter to return to main menu" << end;
cin >> usercontols;
if(usercontrols == 13){
main();
}
}
}
void data_loop(char usercontrols){
cin >> usercontrols;
if (usercontrols == 49){
data_entry();
}
else(usercontrols == 50){
data_recall();
}
}
void writeWorkerInfo(ofstream &stream, float employeenumber, float manhours, float payrate, float gross, float taxes, float net){
stream << " Your ID is " << employeenumber << endl;
stream << " # of hours worked " << manhours << endl;
stream << " Your Hourly rate is " << payrate << endl;
stream << " Your Gross pay is " << gross << endl;
stream << " Your tax rate is " << taxwh << endl;
stream << " Amount of taxes " << taxes << endl;
stream << " Your net pay is " << net << endl;
data_loop();
}
void payrollcalc(float employeenumber, float manhours, float payrate, float gross, float taxes, float net){
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;
//writeWorkerInfo(float employeenumber,float manhours,float payrate,float gross,float taxwh,float taxes,float net);
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open(empnum + ".txt");
writeWorkerInfo(float employeenumber,float manhours,float payrate,float gross,float taxes,float net);
payroll.close();
}
void data_entry(float employeenumber,float manhours,float payrate){
cout << "Enter Employee ID:";
cin >> employeenumber;
cout << "Enter Number of Hours Worked:";
cin >> manhours;
cout << "Enter Pay rate:";
cin >> payrate;
payrollcalc();
}
void data_recall(float employeenumber){
cout << "Enter employee number";
cin >> employeenumber;
///reading in data
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open(empnum + ".txt");
payroll.close();
data_loop();
}
Just get the functions definitions out of the main block code and call them inside main
These points should explain why it's not working:
The function main() needs to return a type.
You are defining all your functions inside main(), place them above main or below with function prototypes.
You are using variables inside functions that aren't declared yet.
Funtions are made so that it can be used in defferent place of the program, making it inside the main scope makes less sense!
Moreover we can't define funtion inside another function, we can just call it from nother fuction that comes after its declaration!
2ndly your main says nothing about returning.
ReturnType FunctionName (dataType args, ...){ FuntionBody}
Refer to the above syntax of a funtion declaration.
A function must always provide its return type as prefix or void if it dont return anything!
Note: In some compiler void main() works just fine, but some compiler says main should return something. So as a standard method you must define main as int not void to safegaurd urself.

ERROR "cannot convert 'float' to 'float...'..."

There are probably other little formatting errors in here that I'll need to fix, etc. but what I need help with is what to do with the following:
Lab8pt1.cpp: In function 'float Salary(float, float)':
Lab8pt1.cpp:48: error: assignment of function 'float Salary(float, float)'
Lab8pt1.cpp:48: error: cannot convert 'float' to 'float ()(float, float)' in assignment
Lab8pt1.cpp:50: error: assignment of function 'float Salary(float, float)'
Lab8pt1.cpp:50: error: cannot convert 'double' to 'float ()(float, float)' in assignment
Lab8pt1.cpp:51: error: cannot convert 'float (*)(float, float)' to 'float' in return
I know it's referring to my Salary function, but I'm not sure what the issue with my float is. This is just supposed to be a simple Lab Assignment that teaches us how to use functions (we only have to write the code for the functions, the rest was given to us).
Help, please! Thanks in advance!
#include <iostream>
#include <iomanip>
#include <string>
using namespace std ;
void Header(void) ;
float Salary(float Hours, float Pay_Rate);
void Print_it(float Hours,float Pay_Rate,float Sal, float Tax_Rate, string Name);
void Read(float &hour, float &Pay_R,string &name) ;
bool Verify(float Hours, float Pay_Rate);
int main ( void )
{
float Pay_Rate, Hours, Sal, Tax;
const float Tax_Rate= (float)0.09 ;
string name;
Header();
for(int i = 0 ; i < 3 ; i++){
Read(Hours,Pay_Rate,name);
Sal = Salary(Hours,Pay_Rate);
Print_it(Hours,Pay_Rate,Sal, Tax_Rate,name);
}
cout<<"\n\n\n**********\t End of report \t*****\n\n\n\n";
return 0 ;
}
void Header( void )
{
string name;
cout << "Welcome, " << name << ", to the Salary Calculator: a program that will calculate your salary.";
return;
}
float Salary(float Hours, float Pay_Rate)
{
if( Hours <= 40 )
Salary = Hours * Pay_Rate;
else if( Hours > 40)
Salary = Hours * (Pay_Rate * 1.5);
return(Salary);
}
void Print_it(float Hours,float Pay_Rate,float Sal, float Tax_Rate, string Name)
{
cout << fixed << setprecision(2);
cout << "Name: " << left << setw(15) << Name << endl;
cout << "Hours worked: " << left << setw(15) << Hours << endl;
cout << "Pay rate: " << left << setw(15) << Pay_Rate << endl;
cout << "Tax rate: " << left << setw(15) << Tax_Rate << endl;
cout << "Salary: " << left << setw(15) << Sal << endl;
return;
}
void Read(float &hour, float &Pay_R,string &name)
{
cout << "Please enter your name: ";
getline(cin, name);
cout << "Please enter number of hours worked: ";
cin >> hour;
cout << "Please enter your pay rate: ";
cin >> Pay_R;
return;
}
bool Verify(float Hours, float Pay_Rate)
{
if( Hours < 0 || Hours > 60 || Pay_Rate < 0 || Pay_Rate > 500)
return false;
else
return true;
}
Salary = Hours * Pay_Rate;
Salary is the function name. You can not assign a float value to it. You need to declare a float variable and return that variable.
float sal;
sal = Hours * Pay_Rate;
return sal;
In fact you don't need this variable. You can directly return within the if-else block.
if( Hours <= 40 )
return Hours * Pay_Rate;
Note that method and variable names should start with a lowercase letter, class name should start with uppercase. This is widely used convention.
its the function you are trying to return.
float Salary(float Hours, float Pay_Rate)
{
if( Hours <= 40 )
Salary = Hours * Pay_Rate;
else if( Hours > 40)
Salary = Hours * (Pay_Rate * 1.5);
return(Salary);
}
there is no variable salary defined in this function
Corrected code is:
float Salary(float Hours, float Pay_Rate)
{
float salary;
if( Hours <= 40 )
salary = Hours * Pay_Rate;
else if( Hours > 40)
salary = Hours * (Pay_Rate * 1.5);
return(salary);
}