I'm trying to left justify one side of a line and right justify the other side of the line, but im having trouble getting the right side to right justify. Could anyone catch my error?
//The following program will declare
#include <iostream>
#include <iomanip>
using namespace std;
const int HOUSING = 3500; //housing cost
const int MEALS = 2000; //meal cost
const int N_CRED_PER = 285; //out of state credit cost
const int CRED_PER = 130; //amount of money per credit(cost)
const int TAB = 30; //precision
const int ADD_FEES = 6200; //out of state fees for non-resident
int main()
{
cout << "Grant Mercer section 1002 Assignment 6\n\n";
int size, studentID, credits, i, valid,total;
//size of loop, studentID to hold ID of student, credits to hold num
//of credits the student will take, i to start loop
char first, last, res, housing, meal; //first and last to hold initials of
//student, res to hold code
//if student is resident, meal to hold
//code if student has meals
cin >> size; //grab length of loop in file
cout << left; //manipulate stream
cout << fixed << showpoint << setprecision(2);
valid = size; //initially all entries are valid, but de
//cremented each time something goes wrong
while (i < size)
{
cin >> studentID >> first >> last >> credits >> res; //read in mandatory data to vars
cout << setw(TAB) << left << "Student #: " << right << studentID << endl; //display id
cout << setw(TAB) << left << "Initials: " << right << first << last << endl;//display initials
if(credits > 0 && credits < 21) //if credits are fine
{
switch(res) //find char in res
{
case 'R': //if RESIDENT
case 'r':
cout << setw(TAB) << left << "Residency status: " << right << "Resident" << endl;
cout << setw(TAB) << left << "Credits: " << right << credits << endl;
cout << setw(TAB-10) << left << "Tuition: " << setw(10) << "$" << right << (double)CRED_PER * credits << endl;
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double)CRED_PER * credits << endl;
total += CRED_PER * credits; //add to total cost
break;
case 'N': //if NON-RESIDENT
case 'n':
cout << setw(TAB) << left << "Residency status: " << right << "Non-resident" << endl;
cin >> housing >> meal; //since the student is non-resident, they
//have a mean and house code
cout << setw(TAB) << left << "Credits: " << right << credits << endl;
cout << setw(TAB - 10) << left << "Tuition: " << setw(10) << "$" << right << (double)credits * N_CRED_PER + ADD_FEES << endl;
if(housing == 'H' || housing == 'h')
{
cout << setw(TAB - 10) << left << "Housing: " << setw(10) << "$" << right << (double)HOUSING << endl;
if(meal == 'M' || meal == 'm') //if MEALS
{
cout << setw(TAB-10) << left << "Meal Plan: " << setw(10) << "$" << right << (double) MEALS << endl;
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double) MEALS + HOUSING + (credits * N_CRED_PER) + ADD_FEES << endl;
total += MEALS + HOUSING + (credits * N_CRED_PER) + ADD_FEES;
//add to total
}
else //if NO MEALS
{
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double)\
HOUSING + (credits *N_CRED_PER) + ADD_FEES << endl;
total += HOUSING + (credits * N_CRED_PER) + ADD_FEES;
//add to total
total += HOUSING + (credits * N_CRED_PER) + ADD_FEES;
//add to total
}
}
else //if NO HOUSING NO MEALS
{
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double)(cr\
edits * CRED_PER) + ADD_FEES
<< endl;
total += (credits * CRED_PER) + ADD_FEES;
}
break;
}
}
else
{
cout << "INVLIAD CREDIT AMOUNT...\n";
valid--;
}
i++;
cout << endl << endl;
}
cout << "\nFINAL TOTALS\n"; //display final totals from students
cout << right << setw(TAB) << left << "Valid request count: " << right << valid << endl;
cout << setw(TAB) << left << "Invalid requrest count: " << right << size - valid << endl;
cout << setw(TAB - 10) << left << "Total feed due: " << setw(10) << "$" << right << (double)total;
cout << endl;
return 0;
}
the output is all left justified, i dont understand what i need to do to make this all right justified. Thanks!
You're forgetting to use setw() before printing each right aligned string with cout. For example, take the following line in your code:
cout << setw(TAB) << left << "Residency status: " << right << "Resident" << endl;
Before printing each string justified to the left or right, you must set a new width:
cout << setw(20) << left << "Residency status: " << setw(20) << right << "Resident" << endl;
Without a setw(), it assumes the width is zero, which basically ignores the right alignment.
Related
I am trying to create a C++ program that calculates sales tax for a customer and displays a receipt. For example, if you entered 10 as the first sale amount and the tax rate is 0.0825 it should display the total tax as $0.83. Why does my subtotal and total due at the end of the receipt display $10.82 when it should be $10.83?
//Customer Receipt
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
struct Item_Receipt
{
double item;
double cost;
double tax;
double subtotal;
};
int main()
{
vector <Item_Receipt> Store_Receipt;
Item_Receipt Purchase;
//Variables
const double item_tax = .0825;
double Item_Total = 0.0;
double Tax_Total = 0.0;
double Total_Sales = 0.0;
int numSales = 0;
cout << "First sales amount (Enter a 0 to stop): ";
cin >> Purchase.item;
Purchase.tax = Purchase.item * item_tax;
Purchase.subtotal = Purchase.item + Purchase.tax;
Store_Receipt.push_back(Purchase);
Item_Total += Purchase.item;
Tax_Total += Purchase.tax;
Total_Sales += Purchase.subtotal;
numSales++;
while (Purchase.item > 0.0)
{
cout << "Next sales amount (Enter a 0 to stop): ";
cin >> Purchase.item;
if(Purchase.item > 0.0)
{
Purchase.tax = Purchase.item * item_tax;
Purchase.subtotal = Purchase.item + Purchase.tax;
Store_Receipt.push_back(Purchase);
Item_Total += Purchase.item;
Tax_Total += Purchase.tax;
Total_Sales += Purchase.subtotal;
numSales++;
}
else
cout << endl << "That was the last item being puchased.\nHere is your itemized receipt." << endl << endl;
}
//end while
//Output
cout << "----------------------------------------- " << endl;
cout << "\tReceipt of Purchase" << endl;
cout << "----------------------------------------- " << endl << endl;
cout << fixed << setprecision(2);
cout << setw(10) << "Item Cost" <<
setw(15) << "Item Tax" <<
setw(15) << "Subtotal" << '\n';
cout << "----------------------------------------- " << endl;
for(int x=0;x<numSales;x++)
cout << setw(8) << Store_Receipt[x].item << setw(15) << Store_Receipt[x].tax <<
setw(15) << Store_Receipt[x].subtotal << endl;
cout << "----------------------------------------- " << endl;
cout << setw(10) << "Item Total" <<
setw(15) << "Tax Total" <<
setw(15) << "Total Due" << endl;
cout << setw(8) << Item_Total << setw(15) << Tax_Total <<
setw(15) << Total_Sales << endl;
cout << "----------------------------------------- " << endl;
cout << "\tYou purchased " << numSales << " items." << endl;
cout << "----------------------------------------- " << endl;
cout << "\tThank you! Have a nice day!" << endl;
cout << "----------------------------------------- " << endl;
cin >> numSales;
return 0;
}
setprecision(2) doesn't mean "round to 2 decimal digits," it means "display 2 decimal digits." The actual value is 10.825 but you're only displaying the first two decimal digits.
If you want to round away from the midpoint, you need to use one of the rounding functions on the result.
Since you want to round to the second decimal place, you have to first multiply the number by 100, then round it, then divide by 100. You could do this with the help of a function:
double round_to_cents(double v) {
return std::round(v * 100) / 100;
}
Then round the tax calculation:
Purchase.tax = round_to_cents(Purchase.item * item_tax);
(Demo)
Here is my code for context. This is my second homework assignment intro to programming course and I have used everything we've learned in this assignment. I am not allowed to use anything I have not learned.
The part I am concerned with is the output at the very bottom (commented as information output). Currently, I am struggling to get everything perfectly right aligned (the last letter or number in the right hand column must align with each other as if I were typing them from the right.
Everything except the patient's name, room type, and days spent in the hospital are aligning properly, decimals aligned and everything. Changing the setw(10) to anything larger does nothing beneficial (ex: i had all of them to setw(40) and it still did not align anything properly. Any ideas?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//constants
const float PRIVATE = 125.00;
const float SEMI = 95.00;
const float WARD = 75.00;
const float TV = 3.50;
const float PHONE = 1.75;
int main()
{ //local variables
string fname, lname, roomType, tvAccess, phoneAccess;
int id, days;
float roomBill, roomPrice, tvCharge, phoneCharge;
bool error = false;
//data collection/output
cout << "Welcome to the hospital self-service program. Your bill will be calculated here.\n\n" << endl;
cout << "Please enter your first and last name: ";
cin >> fname;
cin >> lname;
cout << fname << " " << lname << ", please enter the four digit identification number found on your hospital wristband: ";
cin >> id;
cout << "Please enter the number of days spent in the hospital: ";
cin >> days;
cout << "\nEnter the type of room you stayed in: \nEnter P for room type: Private \nEnter S for room type: Semi-Private\nEnter W for room type: Ward \n" << endl;
cin >> roomType;
cout << "\nDid your room come with access to Television? Y/N: ";
cin >> tvAccess;
cout << "Did your room come with access to a Telephone? Y/N: ";
cin >> phoneAccess;
//if and elses
if (roomType == "P" || roomType == "p")
{
error = false;
roomType = "Private Room";
roomPrice = PRIVATE;
}
else if (roomType == "S" || roomType == "s")
{
error = false;
roomType = "Semi-Private Room";
roomPrice = SEMI;
}
else if (roomType == "W" || roomType == "w")
{
error = false;
roomType = "Ward Room";
roomPrice = WARD;
}
else
{
cout << "Room type not valid. Exit the program and try again." << endl;
error = true;
}
if (tvAccess == "Y" || tvAccess == "y")
tvCharge = TV;
else
tvCharge = 0;
if (phoneAccess == "Y" || phoneAccess == "y")
phoneCharge = PHONE;
else
phoneCharge = 0;
//information output
cout << fixed << setprecision(2) << showpoint << endl;
cout << setw(24) << left << "\n\nPatient Full Name: " << setw(10) << right << fname << " " << lname << endl;
cout << setw(24) << left << "Identification Number: " << setw(10) << right << id << endl;
cout << setw(24) << left << "Days spent in hospital: " << setw(10) << right << days << " day(s)" << endl;
cout << setw(24) << left << "Room Type: " << setw(10) << right << roomType << endl;
cout << setw(24) << left << "Room Charge: " << setw(10) << right << roomPrice * days << endl;
cout << setw(24) << left << "Television Charge: " << setw(10) << right << tvCharge * days << endl;
cout << setw(24) << left << "Telephone Charge: " << setw(10) << right << phoneCharge * days << endl;
cout << setw(24) << left << "Total Charge: " << setw(10) << right << days * (phoneCharge + tvCharge + roomPrice) << endl;
system("pause");
return 0;
}
for clarification.
The reason, they are not formatted correctly, is, that the setw in
setw(10) << right << fname << " " << lname << endl;
and
setw(10) << right << days << " day(s)" << endl;
only applies to the first variable, i.e. fname and days. Everything else is just appended. You need to concatenate these strings first before using setw here.
Lets say you have a data file with multiple entries of struct type data
Based on the code number variable of one of the data entries,you are supposed to draw out the remaining variables of the structure.
Or maybe should I try to find the record number based on the scode?
then using the record number to find the size I need to skip from the beginning using seekg
char scode[MAX];
Subject M;
afile.open (fileName, ios::in | ios::out | ios::binary);
cout << "Enter Subject code: ";
cin >> scode;
cin.clear();
cin.ignore(100,'\n');
cout << endl << endl;
while (afile.read (reinterpret_cast <char *>(&M), sizeof (M)))
{
if (strcmp(scode,M.subCode) == 1)
{
cout << "Subject code not found" << endl;
cout << "----------------------------" << endl;
return;
}
else
{
afile.seekg(-strlen(M.subCode),ios::cur);
cout << "Subject Code: " << M.subCode << endl
<< "Subject Name: " << M.subTitle << endl;
cout << left << setw(8) << "Task"
<< left << setw(14) << "Title"
<< right << setw(7) << "Weight"
<< right << setw(7) << "Upon"
<< right << setw(7) << "Mark"
<< right << setw(12) << "Obtained"
<< endl << endl;
cout << setw (66) << setfill ('-') << "-" << endl;
cout << setfill (' ');
while (afile.read (reinterpret_cast <char *>(&M), sizeof (M)))
{
for (int i = 1; i <= M.noTask; i++)
{
cout << left << setw(8) << i
<< left << setw(14) << M.Task[i].title
<< right << setw(7) << M.Task[i].weight
<< right << setw(7) << M.Task[i].fullmark
<< right << setw(7) << M.Task[i].mark
<< right << setw(12) << M.Task[i].mark / M.Task[i].fullmark * M.Task[i].weight
<< endl;
}
}
}
I'm Using Visual studio (C++) in a class that I am taking, I've had to teach myself functions, and I've hit a small snag in the road that I'd appreciate some advice on.
What I'm having trouble with, is the part of the assignment that states i must
"Utilize a function that prints (not find) the largest/average/smallest commissions"
The way I read this, I'm assuming she only wants it to print, and not do calculations in the function.
A friend suggested I try void print(etc) However I'm unsure how to grab the calculation in main and give it to the function I'm trying to print, or am i going at it all wrong?
I've commented out the portion of code I was trying to function. You can also find it at the very bottom of the code.
Any suggestions/help is greatly appreciated, as most of what I've looked up haven't really dealt with this problem (that I've found)
#include <iostream>
#include <iomanip>
using namespace std;
#define TITLE "Alva's"
#define STANDARD 0.05
#define HYBRID 0.10
#define ELECTRIC 0.15
#define HOLD 50
void dashLine();
int getSalesId();
int runProgram();
char vehicleType();
double sellingPrice();
void print(double largeSmallAverage);
int main()
{
int tot_count,
id_num[HOLD], //* ID
r_ay = 0, //* array
s_count, //*standard
h_count, //*Hybrid
e_count, //*electric
hold_id, //*array Id
compare, //*Pass
change, //*change made when change has value
yesno;
double tot_standard,
tot_hybrid,
tot_electric,
tot_price,
price[HOLD],
hold_price, //*Array hold
comm_l, //* Large
comm_s, //* Small
hold_comm, //*Array hold
avg_comm,
tot_commission,
commission[HOLD];
char car[HOLD],
temp_car;
tot_count = 0;
s_count = 0;
h_count = 0;
e_count = 0;
tot_price = 0;
tot_standard = 0;
tot_hybrid = 0;
tot_electric = 0;
cout << "\n" << TITLE << " Commission Calculator";
yesno = runProgram();
while (yesno == 1)
{
dashLine();
id_num[r_ay] = getSalesId();
car[r_ay] = vehicleType();
price[r_ay] = sellingPrice();
tot_price += price[r_ay];
switch (car[r_ay])
{
case 'S':
case 's':
commission[r_ay] = (price[r_ay] * STANDARD);
tot_standard += commission[r_ay];
s_count++;
break;
case 'H':
case 'h':
commission[r_ay] = (price[r_ay] * HYBRID);
tot_hybrid += commission[r_ay];
h_count++;
break;
case 'E':
case 'e':
commission[r_ay] = (price[r_ay] * ELECTRIC);
tot_electric += commission[r_ay];
e_count++;
break;
}
cout << "\n The commission for this sale, for Employee ID: " << fixed << setprecision(0) << id_num[r_ay] << " is:$ " << fixed << setw(5) << setprecision(2) << commission[r_ay];
cout << "\n";
yesno = runProgram();
r_ay++;
if (r_ay >= HOLD)
yesno = 0;
}
tot_count = (s_count + h_count + e_count);
tot_commission = (tot_standard + tot_hybrid + tot_electric);
{
cout << "\n Number of standard vehicle commissions calculated = " << fixed << setw(8) << setprecision(0) << s_count;
cout << "\n Number of hybrid vehicle commissions calculated = " << fixed << setw(8) << h_count;
cout << "\n Number of electric vehicle commissions calculated = " << fixed << setw(8) << e_count;
cout << "\n Number of vehicle commissions calculated = " << fixed << setw(8) << tot_count;
cout << "\n Total Overall price calculated =$ " << fixed << setw(8) << setprecision(2) << tot_price;
cout << "\n Total amount of standard vehicle commissions =$ " << fixed << setw(8) << tot_standard;
cout << "\n Total amount of hybrid vehicle commissions =$ " << fixed << setw(8) << tot_hybrid;
cout << "\n Total amount of electric vehicle commissions =$ " << fixed << setw(8) << tot_electric;
cout << "\n Total amount of all commissions paid out =$ " << fixed << setw(8) << tot_commission;
cout << "\n";
cout << "\n " << "Sales ID " << "Car type " << "Selling price " << "Commission ";
for (r_ay = 0; r_ay < tot_count; r_ay++)
{
cout << "\n " << fixed << id_num[r_ay] << " " << setprecision(2) << car[r_ay] << " " << setw(10) << price[r_ay] << " " << setw(10) << commission[r_ay];
}
if (tot_count > 0)
{
avg_comm = (tot_commission / tot_count);
comm_s = commission[0];
comm_l = commission[0];
for (r_ay = 1; r_ay < tot_count; r_ay++)
{
if (commission[r_ay] < comm_s)
comm_s = commission[r_ay];
if (commission[r_ay] > comm_l)
comm_l = commission[r_ay];
}
void print(double largeSmallAverage);
//{
// cout << "\n ";
// cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << comm_s;
// cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << comm_l;
// cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << avg_comm;
//}
}
cout << "\n";
change = 1;
compare = tot_count - 1;
do
{
change = 0;
for (r_ay = 0; r_ay < compare; r_ay++)
{
if (commission[r_ay] > commission[r_ay + 1])
{
temp_car = car[r_ay];
hold_id = id_num[r_ay];
hold_price = price[r_ay];
hold_comm = commission[r_ay];
commission[r_ay] = commission[r_ay + 1];
commission[r_ay + 1] = hold_comm;
id_num[r_ay] = id_num[r_ay + 1];
id_num[r_ay + 1] = hold_id;
car[r_ay] = car[r_ay + 1];
car[r_ay + 1] = temp_car;
price[r_ay] = price[r_ay + 1];
price[r_ay + 1] = hold_price;
change = 1;
}
}
compare--;
} while ((compare > 0) && (change == 1));
cout << "\n";
cout << "\n " << "Sales ID " << "Car type " << "Selling price " << "Commission ";
for (r_ay = 0; r_ay < tot_count; r_ay++)
{
cout << "\n " << fixed << id_num[r_ay] << " " << setprecision(2) << car[r_ay] << " " << setw(10) << price[r_ay] << " " << setw(10) << commission[r_ay];
cout << "\n ";
}
system("pause");
return 0;
}
}
void dashLine()
{
cout << "\n -----------------------------------";
}
int getSalesId()
{
int id_num;
cout << "\n Please enter Employee ID: ";
cin >> id_num;
while (id_num < 10000 || id_num > 99999)
{
cout << "\n Invalid Employee ID, Please enter a 5 digit ID ";
cin >> id_num;
}
return id_num;
}
int runProgram()
{
int rp_yesno;
cout << "\n Is there a customer? 1 = yes, 0 = no ";
cin >> rp_yesno;
while ((rp_yesno != 1) && (rp_yesno != 0))
{
cout << "\n Invalid Entry Please enter 1/0 ";
cout << "\n Is there a customer? 1 = yes 0 = no ";
cin >> rp_yesno;
}
return rp_yesno;
}
char vehicleType()
{
char car;
cout << "\n Please enter type of vehicle sold";
cout << "\n (S=standard, H=hybrid, E=electric): ";
cin >> car;
while (!((car == 'S') || (car == 's') || (car == 'h') || (car == 'H') || (car == 'E') || (car == 'e')))
{
cout << "\n Invalid input Please enter S/E/H ";
cin >> car;
}
return car;
}
double sellingPrice()
{
double price;
cout << "\n Please enter the selling price of the car:$ " << fixed << setprecision(2);
cin >> price;
while (price < 1)
{
cout << "\n Invalid entry, Please enter an amount greater than 0 ";
cin >> price;
}
return price;
}
void print(double largeSmallAverage)
{
double comm_s,
comm_l,
avg_comm;
{
cout << "\n ";
cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << comm_s;
cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << comm_l;
cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << avg_comm;
}
}
You would have a function called print that takes has three double parameters: void print(double small, double large, double average);.
Then later on you would call it with print(comm_s, comm_l, avg_comm);.
You need to change the definition of print:
void print(double small, double large, double average)
{
cout << "\n ";
cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << small;
cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << large;
cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << average;
}
I tried to word the title as best as I could. Here I have a function that indexes through two parallel arrays and then outputs them with some formatting.
void outputTable(string salsa_jars[], int jars_sold[], int index[])
{
int totalSold = 0;
cout << setw(8) << "\nSalsa type sells: " << endl
<< "-------------------------------" << endl;
for(int i = 0; i <= (SALSA_TYPES-1); i++)
{
totalSold += jars_sold[index[i]];
cout << setw(15) << left << salsa_jars[index[i]]
<< setw(15) << right << jars_sold[index[i]] << endl;
}
cout << "-------------------------------" << endl
<< "Total sales: " << setw(17) << totalSold << endl;
}
What I'm trying to achieve is to add a string to the first and last outputs of the array. Below is my attempt.
void outputTable(string salsa_jars[], int jars_sold[], int index[])
{
int totalSold = 0;
cout << setw(8) << "\nSalsa type sells: " << endl
<< "-------------------------------" << endl;
for(int i=0;i<=(SALSA_TYPES-1);i++)
{
if(i == 0){
cout << setw(7) << left << salsa_jars[index[i]]
<< "(Highest)" << setw(14) << right
<< jars_sold[index[i]] << endl;
}
else if (i == (SALSA_TYPES-1)){
cout << setw(7) << left << salsa_jars[index[i]]
<< "(Lowest)" << setw(15) << right
<< jars_sold[index[i]] << endl;
}
else{
totalSold += jars_sold[index[i]];
cout << setw(15) << left << salsa_jars[index[i]]
<< setw(15) << right << jars_sold[index[i]] << endl;
}
}
cout << "-------------------------------" << endl
<< "Total sales: " << setw(17) << totalSold << endl;
}
But the code seems redundant, and I couldn't think of any other way to do it. If anyone has any pointers, I would appreciate it. Thanks.
Just prepare appropriate title for entry, and use common logic for displaying it:
for(int i=0;i<=(SALSA_TYPES-1);i++)
{
string title = toString(salsa_jars[index[i]]);
if(i == 0){
title += " (Highest)";
}
else if (i == (SALSA_TYPES-1)){
title += " (Lowest)";
}
totalSold += jars_sold[index[i]];
cout << setw(15) << left << title
<< setw(15) << right << jars_sold[index[i]] << endl;
}
}