Setw(); not outputting what I want with structures

For some reason I can't get setw() to separate each number correctly in my compareExpenses function on lines 65-81. I watched a youtube video of it showing how to make a table and they use setw() the same way. The only difference is they didn't work with structures. I started putting 1 setw() per line because I thought that was the issue. Also I know, I could be using a loop here I understand it's messy, but all I really need to do is format it right.


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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <iostream>
#include <iomanip>


using namespace std;
struct MonthlyBudget
{
	double housing;
	double utilities;
	double householdExp;
	double transportation;
	double food;
	double medical;
	double insurance;
	double entertain;
	double clothing;
	double misc;
};


// Function prototypes
void displayBudget(/*in*/const MonthlyBudget &Budget, double &total);
void getExpenses(/*out*/MonthlyBudget &Spent, string &month);
double validateExpense(/*in*/string);
void compareExpenses(/*in*/const MonthlyBudget &Budget, /*in*/const MonthlyBudget &Spent, double &total, string &month);

int main()
{
    string month;
    double total;

    MonthlyBudget Budget = {580.00, 150.00, 65.00, 50.00, 250.00, 30.00,
                            100.00, 150.00, 75.00, 50.00};
    MonthlyBudget Spent;

    displayBudget(Budget, total);
    getExpenses(Spent, month);
    compareExpenses(Budget, Spent, total, month);





    return 0;
}

void compareExpenses(/*in*/const MonthlyBudget &Budget, /*in*/const MonthlyBudget &Spent, double &total, string &month)
{
    double totalSpent = 0.00;
    string space = " ";

    totalSpent = Spent.housing + Spent.utilities + Spent.householdExp + Spent.transportation
		   + Spent.food + Spent.medical + Spent.insurance + Spent.entertain +
		   Spent.clothing + Spent. misc;

    cout << setprecision(2) << fixed << showpoint;


    cout << setw(52) << right << "Budgeted     Spent      Difference\n";
    cout << "=================================================\n";
    if(&Spent < &Budget)
    {
        double underSpent = 0.00;
        // under spend
        cout << setw(17) << left << "Housing" << right << Budget.housing;
        cout << setw(9) << right << Spent.housing;
        underSpent = Spent.housing - Budget.housing;
        cout << setw(9) << right << underSpent << "\n";
        cout << setw(17) << left << "Utilities" << right << Budget.utilities;
        cout << setw(9) << right << Spent.utilities;
        cout << setw(9) << Spent.utilities - Budget.utilities << "\n";
        cout << setw(17) << left << "Household" << right << Budget.householdExp << space << Spent.householdExp << space << Spent.householdExp - Budget.householdExp << "\n";
        cout << setw(17) << left << "Transportation" << right << Budget.transportation << space << Spent.transportation << space << Spent.transportation - Budget.transportation << "\n";
        cout << setw(17) << left << "Food" << right << Budget.food << space << Spent.food << space << Spent.food - Budget.food << "\n";
        cout << setw(17) << left << "Medical" << right << Budget.medical << space << Spent.medical << space << Spent.medical - Budget.medical << "\n";
        cout << setw(17) << left << "Insurance" << right << Budget.insurance << space << Spent.insurance << space << Spent.insurance - Budget.insurance << "\n";
        cout << setw(17) << left << "Entertainment" << right << Budget.entertain << space << Spent.entertain << space << Spent.entertain - Budget.entertain << "\n";
        cout << setw(17) << left << "Clothing" << right << Budget.clothing << space << Spent.clothing << space << Spent.clothing - Budget.clothing << "\n";
        cout << setw(17) << left << "Miscellaneous" << right << Budget.misc << space << Spent.misc << space << Spent.misc - Budget.misc << "\n";
        cout << "=================================================\n";
        cout << setw(17) << left << "Total" << right << total << space << totalSpent << space << totalSpent - total << "\n";
        cout << "=================================================\n\n";
        cout << "Congratulations! You were $" <<  -1 * (totalSpent - total) << " under budget in " << month << " 2022.\n";
    }
void displayBudget(/*in*/const MonthlyBudget &Budget, double &total)
{
    total = Budget.housing + Budget.utilities + Budget.householdExp + Budget.transportation
		   + Budget.food + Budget.medical + Budget.insurance + Budget.entertain +
		   Budget.clothing + Budget. misc;

    cout << "Here is your monthly budget for YEAR 2022:\n\n";
    cout << setw(15) << left << "Housing"  << "$ "  << right << Budget.housing << "\n";
    cout << setw(15) << left << "Utilities" << "$ " << right << Budget.utilities << "\n";
    cout << setw(15) << left << "Household" << "$ " << right << Budget.householdExp << "\n";
    cout << setw(15) << left << "Transportation" << "$ " << right << Budget.transportation << "\n";
    cout << setw(15) << left << "Food" << "$ " << right << Budget.food << "\n";
    cout << setw(15) << left << "Medical" << "$ " << right << Budget.medical << "\n";
    cout << setw(15) << left << "Insurance" << "$ " << right << Budget.insurance << "\n";
    cout << setw(15) << left << "Entertainment" << "$ " << right << Budget.entertain << "\n";
    cout << setw(15) << left << "Clothing" << "$ " << right << Budget.clothing << "\n";
    cout << setw(15) << left << "Miscellaneous" << "$ " << right << Budget.misc << "\n";
    cout << "=================================================\n";
    cout << setw(15) << left << "Total Budgeted" << "$" << right << total << "\n";
    cout << "=================================================\n";

}

void getExpenses(/*out*/MonthlyBudget &Spent, string &month)
{
    cout << "\nEnter month of expenditure: ";
    cin >> month;
    cout << "Enter actual monthly expenditures for each budget category\n\n";
    cout << setw(15) << left << "Housing:" << "$ ";
    cin >> Spent.housing;
    cout << setw(15) << left << "Utilities:" << "$ ";
    cin >> Spent.utilities;
    cout << setw(15) << left << "Household:" << "$ ";
    cin >> Spent.householdExp;
    cout << setw(15) << left << "Transportation:" << "$ ";
    cin >> Spent.transportation;
    cout << setw(15) << left << "Food:" << "$ ";
    cin >> Spent.food;
    cout << setw(15) << left << "Medical:" << "$ ";
    cin >> Spent.medical;
    cout << setw(15) << left << "Insurance:" << "$ ";
    cin >> Spent.insurance;
    cout << setw(15) << left << "Entertainment:" << "$ ";
    cin >> Spent.entertain;
    cout << setw(15) << left << "Clothing:" << "$ ";
    cin >> Spent.clothing;
    cout << setw(15) << left << "Miscellaneous:" << "$ ";
    cin >> Spent.misc;
    cout << "\n\n";
}

/*  proper output
                 Budgeted     Spent      Difference
=================================================
Housing           580.00      580.00        0.00
Utilities         150.00      130.00      -20.00
Household          65.00       50.00      -15.00
Transportation     50.00       50.00        0.00
Food              250.00      230.00      -20.00
Medical            30.00       30.00        0.00
Insurance         100.00      100.00        0.00
Entertainment     150.00      120.00      -30.00
Clothing           75.00      100.00       25.00
Miscellaneous      50.00       30.00      -20.00
=================================================
Total            1500.00     1420.00       80.00
=================================================
*/

}
actual output:
                 Budgeted     Spent      Difference
=================================================
Housing          580.00     1.00  -579.00
Utilities        150.00     1.00  -149.00
Household        65.00 1.00 -64.00
Transportation   50.00 1.00 -49.00
Food             250.00 1.00 -249.00
Medical          30.00 1.00 -29.00
Insurance        100.00 1.00 -99.00
Entertainment    150.00 1.00 -149.00
Clothing         75.00 1.00 -74.00
Miscellaneous    50.00 1.00 -49.00
=================================================
Total            1500.00 10.00 -1490.00
=================================================

Congratulations! You were $1490.00 under budget in ju 2022.
Last edited on
setw sets the minimum width of the next thing that you output. If you use it before each thing that you output, and use the same width for the same position on each row, then you could think of it as the "column width".

This if(&Spent < &Budget) probably doesn't do what you want. The & operator gives you a pointer to the variable so what this if statement does is that it checks whether the object that Spent refers to is stored before the object that Budget refers to in memory.
(Technically it's UB since they are not part of the same object so you're not actually allowed to compare them)
Last edited on
Ok, I'll try and change the if statement. I just can't figure out why like on line 71 for utilities, I'm not getting a space of 9 adjusted to the right. Something is pushing them together.
jetm0t0 wrote:
Setw(); not outputting what I want with structures

C++20 added the <format> library, it adds to C++ formatting capability C has with printf, etc.

While this sample doesn't deal with structs, it shows how useful std::format can be to create tables:
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
#include <iostream>
#include <format>

int main()
{

   std::cout << "This program calculates n! and the sum of the integers "
             << "up to n for values 1 to limit.\n";

   std::cout << "What upper limit for n would you like? ";
   unsigned int limit {};
   std::cin >> limit;

   // The format string for all rows of the table
   const auto table_format { "{:>8} {:>8} {:>20}\n" };

   // Output column headings
   std::cout << std::format(table_format, "integer", "sum", "factorial");

   for (unsigned long long n { 1 }, sum { 1 }, factorial { 1 };
        n <= limit;
        ++n, sum += n, factorial *= n)
   {
      std::cout << std::format(table_format, n, sum, factorial);
   }
}
This program calculates n! and the sum of the integers up to n for values 1 to limit.
What upper limit for n would you like? 10
 integer      sum            factorial
       1        1                    1
       2        3                    2
       3        6                    6
       4       10                   24
       5       15                  120
       6       21                  720
       7       28                 5040
       8       36                40320
       9       45               362880
      10       55              3628800
If your compiler doesn't yet fully support C++20 there is the {fmt} library.
https://github.com/fmtlib/fmt
You have to set the width for each column, each time.

To make all this easier, I'd start with a function to print a single formatted row. I have intentionally NOT set the widths correctly here. That's an exercise for you:
1
2
3
4
5
6
7
void printRow(const char *label, double budget, double spent)
{
    cout << setw(17) << left << label
         << setw(9) << right << budget
         << setw(9) << right << spent
         << setw(9) << right << spent - budget << '\n';
}


Then change compareExpenses to call printRow():
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
28
29
30
31
32
33
34
35
void compareExpenses(/*in*/const MonthlyBudget &Budget, /*in*/const MonthlyBudget &Spent, double &total, string &mon\
th)
{
    double totalSpent = 0.00;
    string space = " ";

    totalSpent = Spent.housing + Spent.utilities + Spent.householdExp + Spent.transportation
                   + Spent.food + Spent.medical + Spent.insurance + Spent.entertain +
                   Spent.clothing + Spent. misc;

    cout << setprecision(2) << fixed << showpoint;


    cout << setw(52) << right << "Budgeted     Spent      Difference\n";
    cout << "=================================================\n";
    if(&Spent < &Budget)
    {
        // under spend
        printRow("Housing", Budget.housing, Spent.housing);
        printRow("Utilities", Budget.utilities, Spent.utilities);
        printRow("Household", Budget.householdExp, Spent.householdExp);
        printRow("Transportation", Budget.transportation, Spent.transportation);
        printRow("Food", Budget.food, Spent.food);
        printRow("Medical", Budget.medical, Spent.medical);
        printRow("Insurance", Budget.insurance, Spent.insurance);
        printRow("Entertainment", Budget.entertain, Spent.entertain);
        printRow("Clothing", Budget.clothing, Spent.clothing);
        printRow("Miscellaneous", Budget.misc, Spent.misc);
        cout << "=================================================\n";
        printRow("Total", total, totalSpent);
        cout << "=================================================\n\n";
        cout << "Congratulations! You were $" <<  -1 * (totalSpent - total) << " under budget in " << month << " 202\
2.\n";
    }
}


Now you can fiddle with the widths to get them exactly correct.
@Peter87 Totally right, I see the math error now that I'm almost done. It's just comparing memory not referencing because it's a pointer, so I never go to my else statement.

@dhayden Ok TY, I tried what you said, but it looks like I'm off by 1 on a couple lines. Ahhh! so close. It's funny my book I don't think mentions that setw() doesn't work well when using it multiple times on once cout >>. I KNOW my teacher put this formatting in here on purpose, because he knew we may have to dig to find out his method. Here's my updated code, I'm going to look at some of the provided HW examples on comparing 2 data structures, because it says I'm under budget no matter what.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
void getExpenses(/*out*/MonthlyBudget &Spent, string &month)
{
    double spentArray[TEN];

    string userInput;

    cout << "\nEnter month of expenditure: ";
    cin >> month;

    cout << "Enter actual monthly expenditures for each budget category\n\n";
    Spent.housing = validateExpense("Housing:");
    Spent.utilities = validateExpense("Utilities:");
    Spent.householdExp = validateExpense("Household:");
    Spent.transportation = validateExpense("Transportation:");
    Spent.food = validateExpense("Food:");
    Spent.medical = validateExpense("Medical:");
    Spent.insurance = validateExpense("Insurance:");
    Spent.entertain = validateExpense("Entertainment:");
    Spent.clothing = validateExpense("Clothing:");
    Spent.misc = validateExpense("Miscellaneous:");
    cout << "\n\n";
}


double validateExpense(/*in*/string categoryName)
{
    string userInput;
    bool isNegative = false;
    do
    {
        cout << setw(15) << left << categoryName << "$ ";
        isNegative = false;
        cin >> userInput;
        const size_t length = userInput.size();
        for(size_t count1 = 0; count1 < length; count1++)
        {
            if(userInput[count1] == '-')
            {
                cout << "ERROR: You must enter a positive number.\n";
                isNegative = true;
            }
        }
    }while(isNegative == true);

    return stoi(userInput);
}


void compareExpenses(/*in*/const MonthlyBudget &Budget, /*in*/const MonthlyBudget &Spent, double &total, string &month)
{
    double totalSpent = 0.00;

    totalSpent = Spent.housing + Spent.utilities + Spent.householdExp + Spent.transportation
		   + Spent.food + Spent.medical + Spent.insurance + Spent.entertain +
		   Spent.clothing + Spent. misc;

    cout << setprecision(2) << fixed << showpoint;

    cout << setw(52) << right << "Budgeted     Spent      Difference\n";
    cout << "=================================================\n";
    if(&Spent < &Budget)
    {
        // under spend
        cout << setw(17) << left << "Housing" << Budget.housing;
        cout << setw(12) << right << Spent.housing;
        cout << setw(12) << right << Spent.housing - Budget.housing << "\n";
        cout << setw(17) << left << "Utilities" << Budget.utilities;
        cout << setw(12) << right << Spent.utilities;
        cout << setw(12) << Spent.utilities - Budget.utilities << "\n";
        cout << setw(17) << left << "Household" << Budget.householdExp;
        cout << setw(12) << right << Spent.householdExp;
        cout << setw(12) << right << Spent.householdExp - Budget.householdExp << "\n";
        cout << setw(17) << left << "Transportation" << Budget.transportation;
        cout << setw(12) << right << Spent.transportation;
        cout << setw(12) << right << Spent.transportation - Budget.transportation << "\n";
        cout << setw(17) << left << "Food" << Budget.food;
        cout << setw(12) << right << Spent.food;
        cout << setw(12) << right << Spent.food - Budget.food << "\n";
        cout << setw(17) << left << "Medical" << Budget.medical;
        cout << setw(12) << right << Spent.medical;
        cout << setw(12) << right << Spent.medical - Budget.medical << "\n";
        cout << setw(17) << left << "Insurance" << Budget.insurance;
        cout << setw(12) << right << Spent.insurance;
        cout << setw(12) << right << Spent.insurance - Budget.insurance << "\n";
        cout << setw(17) << left << "Entertainment" << Budget.entertain;
        cout << setw(12) << right << Spent.entertain;
        cout << setw(12) << right << Spent.entertain - Budget.entertain << "\n";
        cout << setw(17) << left << "Clothing" << Budget.clothing;
        cout << setw(12) << right << Spent.clothing;
        cout << setw(12) << right << Spent.clothing - Budget.clothing << "\n";
        cout << setw(17) << left << "Miscellaneous" << Budget.misc;
        cout << setw(12) << right << Spent.misc;
        cout << setw(12) << right << Spent.misc - Budget.misc << "\n";
        cout << "=================================================\n";
        cout << setw(17) << left << "Total" << right << total;
        cout << setw(12) << right << totalSpent;
        cout << setw(12) << right << totalSpent - total << "\n";
        cout << "=================================================\n\n";
        cout << "Congratulations! You were $" <<  -1 * (totalSpent - total) << " under budget in " << month << " 2022.\n";
    }
}


/*
output:
Budgeted Spent Difference
=================================================
Housing 580.00 2000.00 1420.00
Utilities 150.00 1.00 -149.00
Household 65.00 1.00 -64.00
Transportation 50.00 1.00 -49.00
Food 250.00 1.00 -249.00
Medical 30.00 1.00 -29.00
Insurance 100.00 1.00 -99.00
Entertainment 150.00 1.00 -149.00
Clothing 75.00 1.00 -74.00
Miscellaneous 50.00 1.00 -49.00
=================================================
Total 1500.00 2009.00 509.00
=================================================

Congratulations! You were $-509.00 under budget in july 2022.

*/
Last edited on
Ok tutor helped me out. This kinda blows my mind. All we really added was a constructor in MonthlyBudget and changed the if statement to (totalSpent < totalBudget). Now the math is working. If I try to explain this it's like trying to superimpose one sheet of paper over another, and then ask the question "do they line up?" instead of some kind of loops that says "does number #1 equal (or less than for this case) number #2. and increment number #1, and number #2". Not to say that my first example means all structure members are compared instantly, but it's just very weird that this works...

Changes:
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
28
29
30
31
32
33
34
35
36
37
38
                                     //after line 17
  	MonthlyBudget() {
      	housing = 0.00;
      	utilities = 0.00;
      	householdExp = 0.00;
      	transportation = 0.00;
      	food = 0.00;
      	medical = 0.00;
      	insurance = 0.00;
      	entertain = 0.00;
      	clothing = 0.00;
      	misc = 0.00;
    }
  	MonthlyBudget(double housing_payment, double utilities_payment, double household_expenses, double transport_payment, double food_payment,
                  double medical_payment, double insurance_payment, double entertainment_payment, double clothing_payment, double misc_payment) {
      	housing = housing_payment;
      	utilities = utilities_payment;
      	householdExp = household_expenses;
      	transportation = transport_payment;
      	food = food_payment;
      	medical = medical_payment;
      	insurance = insurance_payment;
      	entertain = entertainment_payment;
      	clothing = clothing_payment;
      	misc = misc_payment;
    }
};
                                                             //after line 166
totalSpent = Spent.housing + Spent.utilities + Spent.householdExp + Spent.transportation
		   + Spent.food + Spent.medical + Spent.insurance + Spent.entertain +
		   Spent.clothing + Spent.misc; // gets total amount spent
  	totalBudget = Budget.housing + Budget.utilities + Budget.householdExp + Budget.transportation
		   + Budget.food + Budget.medical + Budget.insurance + Budget.entertain +
		   Budget.clothing + Budget.misc; // gets total budget

                                                            //after line 177
 if(totalSpent < totalBudget)


Re MonthlyBudget. You've defined a struct with un-initialised variables and then use a default constructor to initialise. It's easier to initialise when defined - as you would with ordinary variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct MonthlyBudget
{
	double housing {};
	double utilities {};
	double householdExp {};
	double transportation {};
	double food {};
	double medical {};
	double insurance {};
	double entertain {};
	double clothing {};
	double misc {};
};


This sets them all to 0 (default value).
Last edited on
So much repetition gives a hint to how simplifications can be made, including some already suggested above:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <iomanip>

struct MonthlyBudget
{
    static inline std::string category[]
    {
        "Housing", "Utilities", "Household", "Transportation","Food",
        "Medical", "Insurance", "Entertainment", "Clothing", "Miscellaneous",
        "TOTALS"
    };
    
    const int LIMIT{10};
    double* budget = nullptr;
    double* expense = nullptr;
    
    void setBudget(double* a_budget){budget = a_budget;}
    void setExpenses(double* a_expense){expense = a_expense;}
    
    void displayBudget()
    {
        double total_budget{0}, total_expenses{0}, total_difference{0};
        
        std::cout
        << "                 *** BUDGET ****\n"
        << "Category           Budget   Expense      Diff\n"
        << "=============================================\n";
        
        for(int i = 0; i < LIMIT; i++)
        {
            total_budget += budget[i];
            total_expenses += expense[i];
            total_difference = total_expenses - total_budget;
            
            displayLine(i, budget[i], expense[i]);
        }
        std::cout
        << "=============================================\n";
        
        displayLine(LIMIT, total_budget,total_expenses);
    };
    
    void displayLine(int index, double budget, double expense)
    {
        std::cout
        << std::setw(15) << std::left << category[index]
        << std::right << std::setw(10) << std::fixed << std::setprecision(2)
        << budget
        
        << std::right << std::setw(10) << std::fixed << std::setprecision(2)
        << expense
        
        << std::right << std::setw(10) << std::fixed << std::setprecision(2)
        << expense - budget
        
        << '\n';
    }
    
    void enterBudget()
    {
        for(int i = 0; i < LIMIT; i++)
        {
            std::cout
            << "Enter " << category[i] << " amount $";
            std::cin >> budget[i];
        }
    }
    
    void enterExpenses()
    {
        for(int i = 0; i < LIMIT; i++)
        {
            std::cout
            << "Enter " << category[i] << " amount $";
            std::cin >> expense[i];
        }
    }
};



int main()
{
    MonthlyBudget monthly;
    
    // WITH ALREADY PREPARED NUMBERS
    double budget[]
    {580, 150, 65, 50, 250, 30, 100, 150, 75, 50};
    double expenses[]
    {580,130, 50,50 ,230.0, 30,100,120, 100,30};
    
    monthly.setBudget(budget);
    monthly.setExpenses(expenses);
    monthly.displayBudget();
    
    // OR DO IT YOURSELF
    monthly.enterBudget();
    monthly.enterBudget();
    monthly.displayBudget();
    
    return 0;
}



                *** BUDGET ****
Category           Budget   Expense      Diff
=============================================
Housing            580.00    580.00      0.00
Utilities          150.00    130.00    -20.00
Household           65.00     50.00    -15.00
Transportation      50.00     50.00      0.00
Food               250.00    230.00    -20.00
Medical             30.00     30.00      0.00
Insurance          100.00    100.00      0.00
Entertainment      150.00    120.00    -30.00
Clothing            75.00    100.00     25.00
Miscellaneous       50.00     30.00    -20.00
=============================================
TOTALS            1500.00   1420.00    -80.00
Enter Housing amount $480
Enter Utilities amount $250
Enter Household amount $55
Enter Transportation amount $55
Enter Food amount $255
Enter Medical amount $34
Enter Insurance amount $107
Enter Entertainment amount $143
Enter Clothing amount $77
Enter Miscellaneous amount $64
Enter Housing amount $567
Enter Utilities amount $223
Enter Household amount $34
Enter Transportation amount $87
Enter Food amount $265
Enter Medical amount $99
Enter Insurance amount $102
Enter Entertainment amount $149
Enter Clothing amount $12
Enter Miscellaneous amount $67
                 *** BUDGET ****
Category           Budget   Expense      Diff
=============================================
Housing            567.00    580.00     13.00
Utilities          223.00    130.00    -93.00
Household           34.00     50.00     16.00
Transportation      87.00     50.00    -37.00
Food               265.00    230.00    -35.00
Medical             99.00     30.00    -69.00
Insurance          102.00    100.00     -2.00
Entertainment      149.00    120.00    -29.00
Clothing            12.00    100.00     88.00
Miscellaneous       67.00     30.00    -37.00
=============================================
TOTALS            1605.00   1420.00   -185.00
Program ended with exit code: 0


Last edited on
@seeplus Ok, are you saying I don't need my constructor? or that I can replace my structure (lines 2-12) with what you provided? I am still new to finding out you can use functions in your structures, which is weird because my teacher said to never put full functions above main, but I guess with structures, that goes out the window.

@againtry I'm not sure what {0} does on line 25. But I like what you did with lines 29-35, you passed the " i " incrementor to the displayLine function that's nice!

*Oh and I was reading my notes and found an answer about structures:
" Normally value returning functions return back only one value, but there are ways to return more than one value. But they are packaged in such a way that they are treated as a single value."
So I added to my notes this is what a structure does. It can package multiple values and pass them all through a function. Very cool!
Last edited on
@jetm0t0
int x{0}; is the same as int x = 0;
The brackets make variable as well as container/array initialization consistent throughout C++ that way.

I don't plan spending much more time on it but I made some other changes which I'll post shortly for interest sake & FWIW.
FWIW
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <iomanip>

// HEADER
struct MonthlyBudget
{
    static inline std::string category[]
    {
        "Housing", "Utilities", "Household", "Transportation","Food",
        "Medical", "Insurance", "Entertainment", "Clothing", "Miscellaneous",
        "TOTALS" /* LIST CAN BE AMENDED */
    };
    
    const int LIMIT = sizeof(category)/sizeof(std::string) - 1;
    
    double* budget = nullptr;
    double* expense = nullptr;
    
    void setBudget(double* a_budget);
    void setExpenses(double* a_expense);
    void displayBudget();
    void displayLine(int index, double budget, double expense);
    bool enterValues(char selection);
};

// IMPLEMENTATION
void MonthlyBudget::setBudget(double* a_budget){budget = a_budget;}

void MonthlyBudget::setExpenses(double* a_expense){expense = a_expense;}

void MonthlyBudget::displayBudget()
{
    double total_budget{0}, total_expenses{0}, total_difference{0};
    
    std::cout
    << "                 *** BUDGET ****\n"
    << "Category           Budget   Expense      Diff\n"
    << "=============================================\n";
    
    for(int i = 0; i < LIMIT; i++)
    {
        total_budget += budget[i];
        total_expenses += expense[i];
        total_difference = total_expenses - total_budget;
        
        displayLine(i, budget[i], expense[i]);
    }
    std::cout
    << "=============================================\n";
    
    displayLine(LIMIT, total_budget,total_expenses);
    std::cout << '\n';
};

void MonthlyBudget::displayLine(int index, double budget, double expense)
{
    std::cout
    << std::setw(15) << std::left << category[index]
    << std::right << std::setw(10) << std::fixed << std::setprecision(2)
    << budget
    
    << std::right << std::setw(10) << std::fixed << std::setprecision(2)
    << expense
    
    << std::right << std::setw(10) << std::fixed << std::setprecision(2)
    << expense - budget
    
    << '\n';
}

bool MonthlyBudget::enterValues(char selection)
{
    double* array = nullptr;
    
    std::string type;
    
    switch( toupper(selection) )
    {
        case 'B':
            type = "budget";
            array = budget;
            break;
        case 'E':
            type = "expenses";
            array = expense;
            break;
        default:
            std::cout << "*** Invalid budget/expense selection\n";
            return false;
    }
    
    std::cout << "Enter " << type << " items:\n";
    for(int i = 0; i < LIMIT; i++)
    {
        std::cout
        << "Enter " << category[i]
        << " (current amount $" << array[i] <<  ") ";
        std::cin >> array[i];
    }
    std::cout << '\n';
    
    return true;
}

int main()
{
    MonthlyBudget monthly;
    
    // WITH ALREADY PREPARED NUMBERS
    double budget[]
    {580, 150, 65, 50, 250, 30, 100, 150, 75, 50};
    double expenses[]
    {580,130, 50,50 ,230.0, 30,100,120, 100,30};
    
    monthly.setBudget(budget);
    monthly.setExpenses(expenses);
    monthly.displayBudget();
    
    // OR DO IT YOURSELF
    monthly.enterValues('b'); // budget
    monthly.enterValues('E'); // expenses
    monthly.displayBudget();
    
    return 0;
}



                 *** BUDGET ****
Category           Budget   Expense      Diff
=============================================
Housing            580.00    580.00      0.00
Utilities          150.00    130.00    -20.00
Household           65.00     50.00    -15.00
Transportation      50.00     50.00      0.00
Food               250.00    230.00    -20.00
Medical             30.00     30.00      0.00
Insurance          100.00    100.00      0.00
Entertainment      150.00    120.00    -30.00
Clothing            75.00    100.00     25.00
Miscellaneous       50.00     30.00    -20.00
=============================================
TOTALS            1500.00   1420.00    -80.00

Enter budget items:
Enter Housing (current amount $580.00) 678
Enter Utilities (current amount $150.00) 213
Enter Household (current amount $65.00) 78
Enter Transportation (current amount $50.00) 345
Enter Food (current amount $250.00) 123
Enter Medical (current amount $30.00) 98
Enter Insurance (current amount $100.00) 201
Enter Entertainment (current amount $150.00) 23
Enter Clothing (current amount $75.00) 124
Enter Miscellaneous (current amount $50.00) 88

Enter expenses items:
Enter Housing (current amount $580.00) 908
Enter Utilities (current amount $130.00) 23
Enter Household (current amount $50.00) 78
Enter Transportation (current amount $50.00) 93
Enter Food (current amount $230.00) 609
Enter Medical (current amount $30.00) 817
Enter Insurance (current amount $100.00) 22
Enter Entertainment (current amount $120.00) 104
Enter Clothing (current amount $100.00) 85
Enter Miscellaneous (current amount $30.00) 22

                 *** BUDGET ****
Category           Budget   Expense      Diff
=============================================
Housing            678.00    908.00    230.00
Utilities          213.00     23.00   -190.00
Household           78.00     78.00      0.00
Transportation     345.00     93.00   -252.00
Food               123.00    609.00    486.00
Medical             98.00    817.00    719.00
Insurance          201.00     22.00   -179.00
Entertainment       23.00    104.00     81.00
Clothing           124.00     85.00    -39.00
Miscellaneous       88.00     22.00    -66.00
=============================================
TOTALS            1971.00   2761.00    790.00

Program ended with exit code: 0
Last edited on
Topic archived. No new replies allowed.