How can I pass variable objects?

Basically I wrote a program that asks the user for a number of coins they have. It starts by asking how much of each coin we have. Afterwards we print to the screen and do our calculations. I was able to write a function that takes a coin_type and coin_amount for each coin to reduce repetitive checking. It looked really sloppy before.

My question is, Can I pass an object through a function (by object I mean variable not {{Object obj;}} kinda object) with my coin_amount and coin_type.

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
// Bradley Latreille 10/28/17
// MoneyProgram
#include "std_lib_facilities.h"

void toString(string, double);

// Global because of function using all objects
// storage for how much each variable is worth numerically
const double penny{0.01}; // {} assignment in case of narrowing
const double nickel{0.05};
const double dime{0.10};
const double quarter{0.25};
const double half_dollar{0.50};
const double dollar{1.0};   // how much each coin is worth

// storage for how many of each variable we have as a user
int pennies = 0;
int nickels = 0;
int dimes = 0;
int quarters = 0;
int half_dollars = 0;
int dollars = 0;

// storage for how much cash we have total
double TotalCash = 0.0;

int main()
/*
    A program that asks how much money we have, then tells us
    exactly how many of each coin as well as how much total cash
*/
{
    // prompt user for data
    cout << "How many pennies do you have? ";
    cin >> pennies;
    cout << "How many nickels do you have? ";
    cin >> nickels;
    cout << "How many dimes do you have? ";
    cin >> dimes;
    cout << "How many quarters do you have? ";
    cin >> quarters;
    cout << "How many half-dollars do you have? ";
    cin >> half_dollars;
    cout << "How many dollars do you have? ";
    cin >> dollars;

    // force a space in the program for cuteness
    cout << '\n';

    // print our results and complete our calculations
    toString("penny", pennies);
    toString("nickel", nickels);
    toString("dime", dimes);
    toString("quarter", quarters);
    toString("half-dollar", half_dollars);
    toString("dollar", dollars);

    // print total cash at the end of the program
    cout << "\ntotal cash: $" << TotalCash << '\n';
}

// toString - print out our information per coin_type
//            and complete our calculations based on coin_type.
//            I used a function to kill repetitiveness.
void toString(string coin_type, double coin_amount)
{
    if(coin_amount <= 1) {  //singular check
        cout << "You have " << coin_amount
             << " " << coin_type << '\n';
    }else{                  // plural check
        cout << "You have " << coin_amount
             << " " << coin_type << "'s\n";
    }

    // Still want to narrow this down if possible to one line
    if(coin_type == "penny")
        TotalCash += penny * coin_amount;
    if(coin_type == "nickel")
        TotalCash += nickel * coin_amount;
    if(coin_type == "dime")
        TotalCash += dime * coin_amount;
    if(coin_type == "quarter")
        TotalCash += quarter * coin_amount;
    if(coin_type == "half-dollar")
        TotalCash += half_dollar * coin_amount;
    if(coin_type == "dollar")
        TotalCash += dollar * coin_amount;
}


As you can see the function toString gets a type, and amount of our coin but Im still having to do a lot of repetitive checking. I want to narrow that coing_type checking to one line if possible. I don't know if its possible. Pointers? Objects? As you can see my problem is when I try to do that last TotalCash += calculation I dont have any coin_type to reference other than my string to use for checking.

<b> Notice: </b>
std_lib_facilities.h is basically just #include <iostream> and #include <string> as well as using namespace std; incase you wanna run the code just add this stuff and you'll compile. Otherwise you can get the std_lib_facilities.h header contents here: http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
Last edited on
As far as I can tell, this is the shortest way to write this.
I agree with goldenchicken: I like your code as it is.
To shorten it you could use some sort of container which would do the ‘dirty’ job for you, but perhaps you haven’t met them yet.
If the following example doesn’t make any sense for you, it only means what you wrote is a very good code:
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
// Bradley Latreille 10/28/17
// MoneyProgram
#include <iostream>
#include <string>
#include <vector>

double toString(const std::vector<int>& cash);

const std::vector<double> values { 0.01, 0.05, 0.10, 0.25, 0.50, 1.0 };
const std::vector<std::string> names { "pennies",  "nickels",      "dimes", 
                                       "quarters", "half-dollars", "dollars" };

/*
    A program that asks how much money we have, then tells us
    exactly how many of each coin as well as how much total cash
*/
int main()
{
    std::vector<int> wallet(values.size());
    // prompt user for data
    for(unsigned i=0; i<names.size(); ++i) {
        std::cout << "Haw many " << names.at(i) << " do you have? ";
        std::cin >> wallet.at(i);
    }
    std::cout << '\n';

    double totalcash = toString(wallet);
    std::cout << "\ntotal cash: $" << totalcash << '\n';
}

// toString - print out our information per coin_type
//            and complete our calculations based on coin_type.
//            I used a function to kill repetitiveness.
double toString(const std::vector<int>& cash)
{
    double total = 0.0;
    for(unsigned i=0; i<cash.size(); ++i) {
        std::cout << "You have " << cash.at(i) << ' ';
        if(cash.at(i) == 1) {
            if(names.at(i) == "pennies") { std::cout << "penny\n"; }
            else {
                std::string s = names.at(i).substr(0, names.at(i).size()-1);
                std::cout << s << '\n';
            }
        } else { std::cout << names.at(i) << '\n'; }
        total += cash.at(i) * values.at(i);
    }
    return total;
}

@Enoizat

Thanks for a result! I was just curious for fun I don't REALLY need it cut to one line. But your example looks interesting I'll definitely take a go at it and learn whats happening! I just started Vectors slightly, but I haven't reached the Vector chapter in my programming book yet.
Here's an alternative approach (which I tend to favour; I do not like the idea of a function called to_string doing two different unrelated things which the name of the function does not suggest. Also, while learning C++, it is a good idea to try and avoid variables at namespace scope).

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
#include <iostream>

std::string plural_of( std::string coin_name ) // invariant: !coin_name.empty()
{
    if( coin_name.back() == 'y' )
    {
        coin_name.pop_back() ;
        return coin_name + "ies" ;
    }
    else return coin_name + "s" ;
}

void print_coin_count( unsigned int num_coins, const std::string& coin_name )
{
    if( num_coins > 0 ) // print nothing if there are no coins of this type
    {
        std::cout << "You have " << num_coins << ' '
                  << ( num_coins == 1 ? coin_name : plural_of(coin_name) ) << '\n' ;
    }
}

int main()
{
    const std::size_t NUM_COIN_TYPES = 6 ; // note: if arrays have not yet been covered,
                                           // use std::vector<> instead of these two arrays
    const double values[NUM_COIN_TYPES] = { 0.01, 0.05, 0.10, 0.25, 0.50, 1.0 };
    const std::string names[NUM_COIN_TYPES] = { "penny", "nickel", "dime", "quarter", "half-dollar", "dollar" } ;

    unsigned int num_coins[NUM_COIN_TYPES] {} ;
    for( std::size_t i = 0 ; i < NUM_COIN_TYPES ; ++i )
    {
        std::cout << "How many " << plural_of(names[i]) << " do you have? " ;
        std::cin >> num_coins[i] ;
    }

    double total_cash = 0 ;
    for( std::size_t i = 0 ; i < NUM_COIN_TYPES ; ++i )
    {
        print_coin_count( num_coins[i], names[i] ) ;
        total_cash += num_coins[i] * values[i] ;
    }

    std::cout << "\ntotal cash: $" << total_cash << '\n';
}
@JLBorges

I like what you did with the string function plural_of(); Thanks for your result
JLBorges’s code’s always tidy and elegant, but that English grammar compliant function is really a a touch of class.
Topic archived. No new replies allowed.