Cplusplus problem with formatting?
Nov 9, 2018 at 2:16pm UTC
I'm trying to make it so my program lines up 3 things orderly such as
5-------Cakes for $-----59.00
2----Balloons for $-----62.00
(without the -)
I have this
cout << left << setw(6) << cakes
<< right << setw(4) << "Birthday Cakes for $"
<< right << setw(8) << fixed << setprecision(2) << cake_price << endl;
cout << left << setw(6) << balloons
<< right << setw(4) << "Birthday Balloons for $"
<< right << setw(8) << fixed << setprecision(2) << balloon_price << endl;
How can I fix it to be like the one above?
Nov 9, 2018 at 2:42pm UTC
Does this version illustrate your problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
int cakes {5};
int balloons {22};
double cakep {59.0};
double ballp {3.14};
cout.fill('=' );
cout << left << setw(6) << cakes;
cout.fill('_' );
cout << right << setw(24) << "Birthday Cakes for $" ;
cout.fill('#' );
cout << right << setw(8) << fixed << setprecision(2) << cakep << '\n' ;
cout.fill(' ' );
cout << left << setw(6) << balloons
<< right << setw(24) << "Birthday Balloons for $"
<< right << setw(8) << fixed << setprecision(2) << ballp << '\n' ;
}
5=====____Birthday Cakes for $###59.00
22 Birthday Balloons for $ 3.14
Last edited on Nov 9, 2018 at 2:43pm UTC
Nov 9, 2018 at 2:54pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void print( int number, string title, double cost )
{
const int Wnum = 3, Wtitle = 20, Wcost = 6;
if ( number + 0.5 > pow( 10, Wnum ) || title.size() > Wtitle || cost + 0.5 > pow( 10, Wcost - 3 ) )
{
cout << "Unable to format\n" ;
return ;
}
cout << setw( Wnum ) << left << number << " "
<< setw( Wtitle ) << left << title << " for $"
<< setw( Wcost ) << right << setprecision( 2 ) << fixed << cost << '\n' ;
}
int main()
{
print( 5, "Birthday cakes" , 59.0 );
print( 2, "Birthday balloons" , 62.0 );
}
5 Birthday cakes for $ 59.00
2 Birthday balloons for $ 62.00
Nov 9, 2018 at 3:23pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iomanip>
#include <iostream>
struct Item {
int number;
std::string description;
double price;
};
int main() {
Item items[] = {
{ 5, "Cakes" , 59.0 },
{ 2, "Ballons" , 62.0 }
};
std::cout << std::setfill('-' ); // show - between fields for debug
for (const Item& item : items)
std::cout
<< std::setw(2) << item.number
<< std::setw(11) << item.description << " for $"
<< std::setw(5) << std::setprecision(2) << std::fixed << item.price
<< std::endl;
}
Last edited on Nov 9, 2018 at 3:35pm UTC
Topic archived. No new replies allowed.