Avoxy Avoxy - 4 years ago 96
C++ Question

Use a function to return multiple values C++

I have to create a function that will do all the processing (the billsHundred to coinLoonie calculation), but input and output to console will still be done in int main. How should I go about this. I am really having an issue with producing multiple outputs from the function int cash() so i left that blank in order to see what you guys would suggest.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int cash();

int main()
{
int dollarAmount;

for (int i = 1; i <= 3; i++)
{
cout << "Enter the total dollar amount: $";
cin >> dollarAmount;

while (cin.fail())
{
cout << "\nThat entry is not valid. Please try again: ";
cin.clear();
cin.ignore(1000, '\n');
cin.clear();
cin >> dollarAmount;
}

int billsHundred = dollarAmount / 100;
int billsFifty = (dollarAmount - (100 * billsHundred)) / 50;
int billsTwenty = (dollarAmount - (100 * billsHundred) - (50 * billsFifty)) / 20;
int billsTen = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty)) / 10;
int billsFive = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty) - (10 * billsTen)) / 5;
int coinToonie = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty) - (10 * billsTen) - (5 * billsFive)) / 2;
int coinLoonie = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty) - (10 * billsTen) - (5 * billsFive) - (2 * coinToonie)) / 1;

cout << "\nNumber of 100$ bills = " << billsHundred;
cout << "\nNumber of 50$ bills = " << billsFifty;
cout << "\nNumber of 20$ bills = " << billsTwenty;
cout << "\nNumber of 10$ bills = " << billsTen;
cout << "\nNumber of 5$ bills = " << billsFive;
cout << "\nNumber of Toonies = " << coinToonie;
cout << "\nNumber of Loonies = " << coinLoonie << endl << endl;
}
cout << endl;
return 0;
}

int cash()
{


}

Answer Source

There are basically two ways to return multiple values. You either return a struct or class as the return value, or you pass in reference values or pointers and the function sets the referred to/pointed to value.

So if you have to break an amount into 10s and 1s:

struct Change {
    int Tens;
    int Ones;
};

Change cash(int amount) {
    Change result;
    result.Tens = amount / 10;
    result.Ones = amount % 10;
    return result;
}

Change broken = break(15);
// Refer to broken.Tens and broken.Ones.

Alternatively:

void cash(int amount, int& tens, int& ones) {
    tens = amount/10;
    ones = amount%10;
}

int tens;
int ones;
cash(15, tens, ones);

In your application, I would use the struct - a function with seven output arguments has too many arguments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download