Solution for printing information to the screen in c++? - c++

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.

Related

Having some trouble with a assignment in c++

I have a assignment I've been working on and my code is working but the results are off by a hair. I know the issue has to do with rounding but I just can't seem to figure out where the issue lies. I've included the assignment details as well as the results i'm getting versus the expected result. Any help is appreciated.
Link for images https://imgur.com/a/bqIcxfT
'''
// This program will display the size of a population for given number of years
// taking into account annual birth and death rates as well as the number of
// people who move away and move into the area.
#include <iostream>
#include <iomanip>
using namespace std;
//Function prototype
double calculatePop (double, double, double, int, int);
int main ()
{
double P; // Starting population
double B; // Annual birth rate
double D; // Annual death rate
int A; // Average number of people who arrive
int M; // Average number of people who move away
int nYears; // The number of years to display
cout << "This program calculates population change." << endl;
// Set numeric formatting
cout << setprecision(0) << fixed;
// Get starting population size
cout << "Enter the starting population size: ";
cin >> P;
while (P<2){
cout << "Starting population must be 2 or more.";
cout << "Please re-enter:";
cin >> P;}
// Get the annual birth rate
cout << "Enter the annual birth rate (as % of current population): ";
cin >> B;
while (B<0){
cout << "Birth rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> B;}
B/=100;
// Get annual death rate
cout << "Enter the annual death rate (as % of current population): ";
cin >> D;
while (D<0){
cout << "Death rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> D;}
D/=100;
// Get number of people who arrive
cout << "How many individuals move into the area each year? ";
cin >> A;
while (A<0){
cout << "Arrivals cannot be negative.";
cout << "Please re-enter:";
cin >> A;}
// Get number of people who move away
cout << "How many individuals leave the area each year? ";
cin >> M;
while (M<0){
cout << "Departures cannot be negative.";
cout << "Please re-enter:";
cin >> M;}
// Get number of years to see data for
cout << "For how many years do you wish to view population changes? " << endl << endl;
cin >> nYears;
while (nYears<1){
cout << "Years must be one or more.";
cout << "Please re-enter:";
cin >> nYears;}
cout << "Starting population: " << P << endl << endl;
//Display the population to user
for (int y=1; y<=nYears; y++)
{
P = calculatePop(P, B, D, A, M);
cout << "Population at the end of year " << y << " is " << P << ".\n";
}
}
double calculatePop (double P, double B, double D, int A, int M)
{
double N; //New Population Size
N = P + (B*P) - (D*P) + A - M;
return N;
}
'''
The value is correctly calculated but not outputted the same way as in the assignment. Setting setprecision(0) along with fixed will round the number to the nearest integer while the result shown in the assignment is the truncated number. To truncate the result, use
cout << "Population at the end of year " << y << " is " << int(P) << ".\n";

No syntax errors but my program displays weird numbers

Program works and executes everything properly until I get to the part where the function calculates Annual Sales and Quarterly Averages. I'm not sure if the issue is in the function or in the displaying of the information.
The Annual Sales and Average Quarterly Sales display is -6.27744e+66
I feel like I'm missing something obvious.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Company
{
string dName; // Stores Division Name
double firstQSales; // First Quarterly Sales
double sndQSales; // Second Quarterly Sales
double thirdQSales; // Third Quarterly Sales
double fourthQSales; // Fourth Quarterly Sales
double annualSales; // Annual Quarterly Sales
double avgQSales; // Average Quarterly Sales
};
const double NUM_OF_QUARTERS = 4;
void readCorpSales(Company*, int);
void displaySalesData(Company*, int);
void calculateAnnualSales(Company&);
void calculateQuarterlyAvg(Company&);
int main()
{
int corporateSize;
cout << "How many divisions does your corporate has: ";
cin >> corporateSize;
cin.ignore();
while (corporateSize < 0)
{
cout << "Please enter a positive number: ";
cin >> corporateSize;
}
Company* divisions = new Company[corporateSize];
readCorpSales(divisions, corporateSize);
displaySalesData(divisions, corporateSize);
delete[] divisions;
system("pause");
return 0;
}
void readCorpSales(Company *divisions, int a)
{
for (int i = 0; i < a; ++i)
{
cout << "Enter division's name: ";
cin >> divisions[i].dName;
cout << "Enter 1st quarter sales: ";
cin >> divisions[i].firstQSales;
cout << "Enter 2nd quarter sales: ";
cin >> divisions[i].sndQSales;
cout << "Enter 3rd quarter sales: ";
cin >> divisions[i].thirdQSales;
cout << "Enter 4th quarter sales: ";
cin >> divisions[i].fourthQSales;
cout << "\n";
}
}
void displaySalesData(Company* divisions, int a)
{
cout << "\n===============================";
cout << "\n Corporate Data Sales Report";
cout << "\n===============================\n";
cout << "\nDivision Name";
cout << "\t 1st Q ($)";
cout << "\t 2nd Q ($)";
cout << "\t 3rd Q ($)";
cout << "\t 4th Q ($)";
cout << "\t Annual Sales ($)";
cout << "\t Avg Q Sales ($)\n";
for (int i = 0; i < a; ++i)
{
cout << divisions[i].dName << "\t";
cout << divisions[i].firstQSales << "\t";
cout << divisions[i].sndQSales << "\t";
cout << divisions[i].thirdQSales << "\t";
cout << divisions[i].fourthQSales << "\t";
cout << divisions[i].annualSales << "\t";
cout << divisions[i].avgQSales << "\n";
}
}
void calculateAnnualSales(Company &divisions)
{
divisions.annualSales = divisions.firstQSales + divisions.sndQSales + divisions.thirdQSales + divisions.fourthQSales;
}
void calculateQuarterlyAvg(Company &divisions)
{
divisions.avgQSales = divisions.annualSales / 4;
}
Regarding the garbage value, maybe you can refer to this or this.
Other thing, the answer from M.M covered the question

If statement inside loop not reading total right cout displaying wrong

Hello all I want to do is for last cout statement display whatever apartment has the highest rent and the apartment name. Right now it displays the total rent of all complexes enter and whatever the last complex name entered. I am stuck on this and could really use some help on this. I am new to c++ so please talk to me in layman terms it is hard for me to understand somethings.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("rentfile.txt");
int numComplex, numMonths;
double rent, totalAllRent = 0; //// Accumulator for total scores
string nameComplex;
string highNameComplex;
double averageRent;
double highestRentTotal = 0;
//set up numeric output programing
cout << fixed << showpoint << setprecision(1);
cout << "How many complexes will you enter?";
cin >> numComplex; //number of complexes enter
cout << "How many months of rent will you enter complex?";
cin >> numMonths; //number of months of rent enter
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
outputFile << rent << endl; //write data to output file
totalAllRent = totalAllRent + rent;
if (totalAllRent > highestRentTotal)
{
highNameComplex = nameComplex;
highestRentTotal = totalAllRent;
}
averageRent = totalAllRent / numComplex;
}
}
outputFile.close(); //close the file
ifstream inputFile;
inputFile.open("rentfile.txt");
cout << "Complex Monthly rent Collected per Complex " << endl;
while (inputFile >> nameComplex)
{
for (int i = 0; i < numMonths; i++)
{
inputFile >> rent;
cout << nameComplex << " " << rent << endl;
if (rent == 0)
cout << "Warning one of the complexes submitted zero rent for one of the months " << endl;
}
}
cout << "Total rent collected for the company = " << totalAllRent << endl;
cout << " Average Monthly rent collected for the company = " << averageRent << endl;
cout << highNameComplex << "collect the most rent = " << highestRentTotal << endl;
system("pause");
return 0;
}
Well...if it's me, I'll design the program as follows:
1. Define a vector<vector<double>> vvRents for storing the rents of all apartments by month.
2. Each element in vvRents stores the rents of all months of each apartment.
3. Once all data is collected, calculate summed rents of the year by apartment, and store the total rents in a new vector vTotalRents.
4. Use a max_element algorithm to pick the most expensive apartment.
You must include <vector> to use vector class, and include <algorithm> to use max_element.

C++: interestEarned coming back wrong

I'm learning C++ and this is an assignment I have to do, it's complete but my interestEarned is not coming back correctly but the bankBalance is correct so I'm just not displaying interestEarned correctly. "Total Interest Earned: $65.50" is incorrect is supposed to display "$120.50" as my teacher said. What am I doing wrong?
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Variables
int numOfCustomers, numOfMonths = 0;
double bankBalance, depositAmount, withdrawnAmount, interestRate, interestEarned = 0.0;
const int MIN = 0;
// Asking for Number of Customers
cout << "Enter the number of customers: ";
cin >> numOfCustomers;
// Making sure the input was not 0 or lower
while (numOfCustomers <= MIN) {
cout << "==>Number of customers must be at least 1. Try again: ";
cin >> numOfCustomers;
}
// Validating each Customer
for (int c = 1; c < (numOfCustomers + 1); c++) {
// Start of each Customer
cout << "\nCUSTOMER " << c << ":\n";
// Asking for Number of Months --
cout << "Enter the number of months the account has been opened: ";
cin >> numOfMonths;
// Making sure the input was not 0 or lower
while (numOfMonths <= MIN) {
cout << "==>Number of months must be at least 1. Try again: ";
cin >> numOfMonths;
}
// Asking for Starting Balance --
cout << "Enter the starting balance: $";
cin >> bankBalance;
// Making sure the input was not 0 or lower
while (bankBalance < MIN) {
cout << "==>Starting balance can't be negative. Try again: $";
cin >> bankBalance;
}
// Asking for Monthly Interest Rate --
cout << "Enter the monthly interest rate as a decimal (i.e. 0.05 = 5%): ";
cin >> interestRate;
// Making sure the input was not 0 or lower
while (interestRate < MIN) {
cout << "==>Monthly interest rate can't be a nagative. Try again: ";
cin >> interestRate;
}
// Validating each Month
for (int m = 1; m < (numOfMonths + 1); m++) {
// Deposit Amount
cout << "\nEnter deposit amount for Month " << m << ": $";
cin >> depositAmount;
bankBalance = bankBalance + depositAmount;
// Withdrawn Amount
cout << "Enter withdrawn amount for Month " << m << ": $";
cin >> withdrawnAmount;
bankBalance = bankBalance - withdrawnAmount;
// Calculating Interest Earned
interestEarned = bankBalance * interestRate;
// Complete bankBalance
bankBalance = bankBalance + interestEarned;
}
// Account Summary
cout << "\nACCOUNT SUMMARY" << endl;
cout << fixed << setprecision(2);
cout << "Number Months Active: " << numOfMonths << endl;
cout << "Ending Balance: $" << bankBalance << endl;
cout << "Total Interest Earned: $" << interestEarned << endl;
}
system("pause");
return 0;
}
Use another variable that is initialized to zero before the loop. In the loop, add the value of interestEarned to it. - #Peter

How can I get user input to exit a loop?

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)