André Fecteau
André Fecteau

Reputation: 140

Output based on variable

I am in an intro to Computer science course learning C++. Our current project involves taking input of what type of bank account the person has (commercial or personal) and following different paths for both. I have found that this would cause me to write two output functions, one for each different type of account.

Would there be a way for me to write 1 output function but have it output the information based on what type of account they chose?

For example what I was thinking of would be to give each choice a number. This example would be personal is 0 and Commercial is 1. When they enter what type it assigned the number 1 or 0 to a variable and then each variable I output would be based off a if statement that says if X is equal to 1 then output Y if not output Z.

Any help would be appreciated and if this is unclear I can provide more information about the project.

Thanks.

Upvotes: 0

Views: 80

Answers (2)

Zach Stark
Zach Stark

Reputation: 575

Yes, there certainly is such a way to do that. Without needing to make separate classes for CommercialAccounts and PersonalAccounts, inheritance, et cetera, you can just do

#define COMMERCIAL 0
#define PERSONAL 1

void printAccount(int account_type /* add parameters for the actual account data */) {
  switch(account_type) {
  case COMMERCIAL:
    // do stuff...
    break;
  case PERSONAL:
    //do stuff...
    break;
  default:
    std::cerr << "Error: " /* invalid input error message */ << std:: endl;
  }
}

Upvotes: 0

Jay
Jay

Reputation: 14441

a template to help you get started:

enum AccountType { Checking, Savings };

void Output( AccountType userAccount )
{
  switch ( userAccount )
  {
     case Checking:
     // do something here for checking accounts
     break;
     case Savings:
     // do something here for savings accounts
     break;
  }
}

There are definitely other ways, but this is simple to understand.

Upvotes: 1

Related Questions