For a lab of mine we need to display the output values in a column following a statement of what the value is for.
Example of what I need.
Amount of adult tickets: 16
Amount of children tickets: 12
Revenue from ticket sales: $140.22
I am trying to use setw like
cout << "Amount of adult tickets: " << setw(15) << ticketsAdult` << endl;
cout << "Amount of children tickets: " << setw(15) < ticketsChildren << endl;
I'm assuming either setw is the wrong thing to use for this or I'm using it wrong as it usually results in something like
Amount of adult tickets: 16
Amount of children tickets: 12
What can I use to make the values to the right all align like they did in the example no matter the length of the "Amount of..." statements before each of them?
It looks like there is right and left alignment too. Other than that it looks like it's a pain to use.
C++ iomanip Alignment
Combining everything said together
#include <iostream>
#include <iomanip>
int main()
{
int ticketsAdult = 16;
int ticketsChildren = 12;
double rev =140.22;
std::cout << std::setw(35) << std::left << "Amount of adult tickets: " << ticketsAdult << '\n';
std::cout << std::setw(35) << std::left << "Amount of children tickets: " << ticketsChildren << '\n';
std::cout << std::setw(35) << std::left << "Revenue from ticket sales: " << '$' << rev << '\n';
return 0;
}
Related
I'm asking this after googling for 2 hours now. As the title says I think I'm misunderstanding how to use the two things above. I'm attempting to create two distinct columns that show output and are in line with one another. However it seems no matter what I do they won't line up.
My code is as follows
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
const double THEATHERCUT = .80;
const double DISTRIBUTORCUT = .20;
const int CHILDCOST = 6;
const int ADULTCOST = 10;
string movieName;
int childTickets, adultTickets, childGrossRevenue, adultGrossRevenue, totalGrossRevenue, distributorRevenue, totalNetRevenue;
//User Input
cout << "What movie was viewed?" << endl;
getline(cin, movieName);
cout << "How many adult tickets were sold?" << endl;
cin >> adultTickets;
cout << "How many child tickets were sold?" << endl;
cin >> childTickets;
// Maths
childGrossRevenue = (CHILDCOST * childTickets);
adultGrossRevenue = (ADULTCOST * adultTickets);
totalGrossRevenue = (childGrossRevenue + adultGrossRevenue);
distributorRevenue = (totalGrossRevenue * .20);
totalNetRevenue = (totalGrossRevenue * .80);
cout << left << "Movie Name:" << setw(20) << right << movieName << endl;
cout << left << "Adult Tickets Sold:" << setw(20) << right << adultTickets << endl;
cout << left << "Child Tickets Sold:" << setw(20) << right << childTickets << endl;
cout << left << "Gross Box Office Revenue:" << setw(20) << right << totalGrossRevenue << endl;
cout << left << "Amount Paid to Distributor:" << setw(20) << right << distributorRevenue << endl;
cout << left << "Net Box Office Revenue:" << setw(20) << right << totalNetRevenue << endl;
system("pause");
return 0;
}
As far as my understanding goes the first cout line should do the following:
Align "Movie Name:" to the left, setw(20) set a 20 space padding between the "Movie Name:" and movieName. right then justifies movieName to the right. Is this correct? Just for clarification this is how I'd like it to look.
(I'm also well aware using system("pause") is sacrilegious before anyone mentions it.)
setw(20) set a 20 space padding between the "Movie Name:" and movieName. right then justifies movieName to the right. Is this correct?
No.
setw(20) sets the next "field" to be 20-characters wide, triggering the insertion of additional whitespace if the field is shorter (resulting in an "alignment" effect in the output of subsequent fields).
This must come before the field is inserted otherwise you have a temporal paradox.
The field you're trying to pad is the "Movie Name:" part, so move your setws one to the left.
left and right align within a field, which doesn't seem to be what you are after, so drop right.
(live demo*)
* I have killed two unused variables, fixed indentation, remove sacrilegiousness (I literally had to or this demo wouldn't work — evil!), and increased your spacing (since 20 isn't actually enough to fit column 1 in all your rows). Otherwise the changes are only as recommended above.
My program executes just fine, but I was wondering how to align my output so cents line up rather than dollars.
We've only started class a couple weeks ago, so we haven't gone over this yet. My professor says it's okay for now if they don't align, I guess I'm just OCD about it. Plus, I think it looks a lot cleaner.
Also, if the bill is $38.40, would that be four significant figures? Sorry, I haven't taken math in a while. In my output, I'm getting up to five significant figures for some reason. The most I have is four. How would I fix this, using setprecision?
cout << "Bill \t \t $ " << bill << endl;
cout << "Tax at 10.5% \t \t $"<<tax<< endl;
cout << "Sub-total \t \t $"<<subTotal<< endl;
cout << "Tip at 20% \t \t $"<<tip<< endl;
cout << endl;
cout << "Total Bill \t \t \t $"<<totalBill<< endl;
As you see, I've been trying it using the tab escape. As a reply suggests, I should use setw?
Edit for 9/10:
I've gotten all my dollar amounts rounded to two decimals, except for the bill, and I don't know how to fix it. Thanks for all the info you've given me, but it's too advanced for what we're doing right now, so I've just aligned things manually. I still need to add setw and then fix everything once that's there. I'm just asking about why the bill is only three digits. It's probably something super simple that's going right over my head.
// Declare variables
double bill, tax, subTotal, tip, totalBill;
// Variables
bill = 38.40;
tax = .105;
tip = .20;
// Calculate the tax
tax = bill * .105;
// Calculate sub-total of bill
subTotal = bill + tax;
// Calculate tip
tip = subTotal * .20;
// Calculate total amount of bill
totalBill = subTotal + tip;
cout << "Bill" " $ " << setprecision(4) << bill << endl;
cout << "Tax at 10.5%" " $ " << setprecision(3) << tax << endl;
cout << "Sub-total" " $ " << setprecision(4) << subTotal << endl;
cout << "Tip at 20%" " $ " << setprecision(3) << tip << endl;
cout << endl;
cout << "Total Bill" " $ " << setprecision(4) << totalBill << endl;
Edit: I "fixed" it. All is good now.
If you're printing money, I recommend you look at C++'s money I/O.
std::put_money will ensure you are international compliant and printing with correct rounding/precision.
Set the locale of std::cout for USD.
std::showbase will decide whether to print the $.
//settings for printing as USD
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << std::showbase;
Use std::setw and std::left for formatting.
Here is an example of printing your data:
#include <iostream>
#include <string>
#include <iomanip>
//row data from example
struct Row{
std::string description;
float amount;
};
//function for printing a row
void Print(Row row);
int main(){
//example rows
Row a{"Bill",3840};
Row b{"Tax at 10.5%",403};
Row c{"Sub-total",4243};
Row d{"Tip at 20%",848};
Row e{"Total Bill",5091};
//settings for printing as USD
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << std::showbase;
//format printing
Print(a);
Print(b);
Print(c);
Print(d);
std::cout << '\n';
Print(e);
}
void Print(Row row){
static const int COLUMN_WIDTH{14};
std::cout << std::setw(COLUMN_WIDTH) << std::left << row.description;
std::cout << " " << std::right << std::put_money(row.amount) << '\n';
}
result:
Bill $38.40
Tax at 10.5% $4.03
Sub-total $42.43
Tip at 20% $8.48
Total Bill $50.91
One possible way is to use setw.
cout<<setw(5)<<4.55<<endl;
cout<<setw(5)<<44.55<<endl;
output:
4.55
44.55
Update:
as Jonathan Leffler pointed out, the << operator resets the width, hence the code is updated to show it should be repeated.
I would do something like:
std::cout << std::setw(15) << std::left << "Bill";
std::cout << std::setw(15) << std::right << std::fixed << std::setprecision(2) << bill << std::endl;
std::cout << std::setw(15) << std::left << "Tax # 10.5%";
std::cout << std::setw(15) << std::right << std::fixed << std::setprecision(2) << tax << std::endl;
This sets the width of the output for each "column" to 15 characters so you don't have to rely on tabs. All of the the "labels" will be left justified, and all of the prices will be right justified and printed to 2 decimal places. This is a bit more robust than relying on tabs, where you don't have control as to how many characters are used. You can't do proper justification with tabs.
I have my program doing 90% of what I want all that is left to do is get the total by adding all my subtotals and outputting to a file. It my be something simple but I can't seem to find a way to get the total of all my subtotals added together. To be honest, even though I need to make it output into a text file I have not attempted anything yet because I was trying to figure a way to get my total. Would someone mind finding me a solution and explaining it so I get a better understanding.
//Libraries
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream theFile("input.txt");
string name;
int units;
double price, subtotal;
cout << "\n" <<string(80, '*') << endl;
cout.width(66); cout << "Inventory Report For Jane Doe International Hardware" << endl;
cout << string(80, '*') << "\n" << endl;
cout << left << setw(20) << "ITEM";
cout << right << setw(20) << "NUMBER OF UNITS";
cout << right << setw(20) << "UNIT COST ($)";
cout << right << setw(20) << "TOTAL VALUE ($)" << endl;
cout << string(80, '-') << "\n" <<endl;
cout << fixed;
cout << setprecision(2);
while (theFile >> name >> units >> price) {
subtotal = units*price;
cout << left << setw(20) << name << right << setw(15) << units << right << setw(20) << price << right << setw(20) << subtotal <<endl;
}
cout << "\n" <<string(80, '-') << endl;
cout <<left << setw(20) << "Inventory Total ($)" << right << setw(55) << "total" <<endl;
return 0;
}
My input text file
Chisel 50 9.99 Hammer 30 15.99 Nails 2000 0.99
Bolts 200 2.99 Nuts 300 1.99 Soap 55 1.89
You need to sum up all subtotals. However, each subtotal is only accessible in its iteration, afterwards, it's lost since you reassign subtotal.
Hence, declare a variable total outside of your while loop, then add the subtotal to the total in each iteration. Thus, add the following line
subtotal = units*price;
total += subtotal;
Now you can print total later on.
I've been trying to align the following code for the last 3 hours with zero success. Could anybody fill me in about what I'm doing wrong?
My aim is to have the string literal left aligned and the variable right aligned like this:
Loan amount: $ 10000.00
Monthly Interest Rate: 0.10%
But this is what I keep geting:
Loan amount: $ 10000.00
Monthly Interest Rate: 0.10%
And this is the most recent version of what I've been trying:
cout << setw(25) << "Loan amount:" << right << "$ "<< amount << endl;
cout << setw(25) << "Monthly Interest Rate:"<< right<< rateMonthly << "%" << endl;
I would really appreciate some help.
The setw field width is defined for the next item to be output and is reset to 0 afterwards. This is why only the text is displayed on 25 chars and not the remaining output on the line.
The right and left justifier define where the fill chars are to be put in the field. This means that it applies only to the current field if it has a defined width. This is why the justification is not applied to the items following the text.
Here you to obtain the expected result:
cout <<setw(25)<< left<< "Loan amount:" << "$ "<< setw(10)<<right << amount << endl;
cout <<setw(25)<< left << "Monthly Interest Rate:"<<" "<<setw(10)<<right<< rateMonthly << " %" << endl;
If you want the $ to be next to the number, you have to make sure that the $ and the number are concatenated into a single object to output, either by puting them together in a single string, or by using monetary format.
Here's the live demo, which should output exactly what you want.
There's no way to set the precision with std::to_string(double), that's why I've created a small helper to do it.
auto to_string_precision(double amount, int precision)
{
stringstream stream;
stream << fixed << setprecision(precision) << amount;
return stream.str();
};
cout << setw(25) << left << "Loan amount:" << setw(10) << right << ("$ " + to_string_precision(amount, 2)) << endl;
cout << setw(25) << left << "Monthly Interest Rate:" << setw(10) << right << (to_string_precision(rateMonthly, 2) + "%") << endl;
Alternative, I still think this one looks better:
cout << setw(25) << left << "Loan amount:" << "$ " << amount << endl;
cout << setw(25) << left << "Monthly Interest Rate:" << rateMonthly << "%" << endl;
If you want
Loan amount: $ 10000.00
Monthly Interest Rate: 0.10%
If you don't want to bother with left and right you can use
cout << "Loan amount:" <<setw(25)<< "$ "<< amount << endl;
cout << "Monthly Interest Rate:"<< setw(19)<< rateMonthly << "%" << endl;
You can use the following
cout << setw(25) << left << "Loan amount:"<< "$ " << amount << endl;
cout << setw(28) << left << "Monthly Interest Rate:" << rateMonthly << "%" <<endl;
I have been working on this program for awhile, but it refuses to cooperate on this last little stretch. The point of the program is to sift a data file into three arrays, sort the arrays, then print them out into a table. The problem I'm having appears to be with the table. The program is divided into four functions, and when I attempt to debug, it won't show the productName array in the function.
The malfunctioning segment of code looks like this:
void printReport (string productName[], int numberinStock[], float price[], int number_of_products)
{
float totalPrice;
cout << setw(18) << " " << "Friendly Grocer Store Inventory" << setw(17) << " " << endl;
cout << setw(18) << "Inventory Item" << setw(16) << "Number in Stock" << setw(16) << "Unit Price" << setw(16) << "Total Sales" << endl;
for (int count=0; count <number_of_products-1; count++)
{
cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << setw(16) << std::setprecision(2) << price[count] << setw(16) << std::fixed << std::setprecision(2) << price[count]*numberinStock[count] << endl;
}
cout << "Total Price: " << totalPrice;
}
It will print everything else, but not the productName.
Some debugging statements outside of the for loop like cout << productName[1] will print out the proper productName but it's completely blank on the actual report.
After some debugging it seems like after printing the productName in the for loop every item after that overwrites the product name.
For example just leaving cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << endl;
will produce
" 3s"
" 10h"
" 2a"
The product names there are Mangoes, Sandwich, and pizza.
I'm at a loss. Where did I mess up?
You might have screwed up passing the data into the function. If you set up test arrays in the function it should be printing correctly.
To pass arrays in C++ use the arrayname.
eg
int main ()
{
string productName[] = {"mango"};
...
printReport(productName, numofProduct);
return 0;
}