Calling c++ functions - c++

this is my first question here on stackoverflow so I hope it all comes out formatted correctly. I'm working on an assignment for my programming course and we have to write a program that takes two inputs and then produces a readout of results. I had to create two functions that ask which concert a person would like to attend and then how many tickets they would like to purchase for that concert. I've created the functions but now I'm having trouble calling the functions in order to print my results.
#include <iostream>
using namespace std;
char GetConcert()
{
char Concert;
cout << "The following concerts are available:\n";
cout << " B for Beyonce\n";
cout << " L for Lady Gaga\n";
cout << " T for Taylor Swift\n";
cout << "Enter the letter for the concert you want:\n";
cin >> Concert;
return Concert;
}
int GetNumTickets()
{
int NumTickets;
cout << "Enter the number of tickets you want:\n";
cin >> NumTickets;
while ((NumTickets < 0) || (NumTickets > 10))
{
if (NumTickets < 0)
cout << "You can not sell tickets here.\n";
else if (NumTickets > 10)
cout << "You may not purchase more than 10 tickets.\n";
cout << "Enter the number oftickets you want:\n";
cin >> NumTickets;
}
return NumTickets;
}
int main()
{
// Declare Variables
char Concert;
int NumTickets;
// Call function to find out the concert they want to attend
// Call function to find out how many tickets they want
// Print out the information you have collected.
cout << "\nThe customer has placed the following order:\n";
cout << "Concert: " << Concert << endl;
cout << "Number of Tickets: " << NumTickets << endl;
return 0;
}
I've declared my variables in the main section, but when I try to call the function, it says that I can't switch from integer to character.

In order to call a function in c++ you need () at the end of the function name. In this example GetNumTickets() and GetConcert(). Since these functions are also returning values, it is important to save the returned values in order to use them later or to use them right away. You could try:
char Concert = GetConcert();
int NumTickets = GetNumTickets();

Related

How to multiply/divide one function to another ? How to use parameters?

How do I multiply a function to another function? and how do I properly use parameters?
I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.
Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.
For example:
float mealMath(numberOfAdults, mealChoosing){
//Rest of function
}
but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!
int numberOfAdults(){
int totalAdults;
cout << "Now how many adults will there be?: ";
cin >> totalAdults;
cout << "It seems there will be: " << totalAdults << " Adults." << endl;
while(totalAdults < 1){
cout << "Sorry there has to be a minimum of 1 adult!" << endl;
cout << "How many adults: ";
cin >> totalAdults;
}
return 0;
}
int numberOfKids(){
int totalKids;
cout << "Now how many Kids will there be?: ";
cin >> totalKids;
cout << "It seems there will be: " << totalKids << " kids." << endl;
while(totalKids < 0){
cout << "Sorry there has to be a minimum of 1 Kid!" << endl;
cout << "How many Kids: ";
cin >> totalKids;
}
return 0;
}
float mealChoosing(){
float cost;
string mealChoise;
cout << " " << endl;
cout << "Now, What meal will you be getting(D/S): ";
cin >> mealChoise;
if(mealChoise == "D"){
cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
cost = 25.95;
}
if(mealChoise == "S"){
cout << "It seems you have selected the Standard Meal plan for everyone!" << endl;
cost = 21.75;
}
cout << " " << endl;
return cost;
}
One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"
So I want numberOfAdults * mealChoosing but I want that done in a different function so
"float total(){
float totalBill;
totalBill = numberOfAdults * mealChoosing;
cout << totalBill;"
or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:
float mealMath(int a, float b){/*Your code here*/}
And then later call mealMath with the other two functions passed as arguments.
float x = mealMath(numberOfAdults(), mealChoosing());
Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.
It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.
Like mealChoosing() return totalAdults and totalKids (although its not needed here) from numberOfAdults(), numberOfKids() respectively.
int numberOfAdults() {
//...
return totalAdults;
}
int numberOfKids() {
//..
return totalKids;
}
float mealChoosing() {
//..
return cost;
}
Now on mealMath(numberOfAdults, mealChoosing)
float mealMathOutput = mealMath(numberOfAdults(), mealChoosing());

More efficient use for a function that determines winner on user input

So in my programming class lab, I was asked this question: "Write a program that prompts users for the name and number of points of two basketball teams. Then, it uses a nested if to display the winner (if any) or a message stating a tie if both teams have the same number of points – One screen shot per scenario – use one function to determine the possible scenarios. "
I got the answer, but I feel as though it could greatly be condensed and the only reason I put a function in is because it is required. I would like some help on how to make this function more efficient and useful for future code. Any tips would be much appreciated! (code below)
#include <iostream>
#include <string>
using namespace std;
string bballTeam1;
string bballTeam2;
int scoreCheck(int, int);
int main() {
int winner;
int score1 = 0;
int score2 = 0;
cout << "Enter a basketball team name: ";
getline(cin, bballTeam1); //had to make sure to account for spaces
cout << endl;
cout << "Enter a basketball team name: ";
getline(cin, bballTeam2); //had to make sure to account for spaces
cout << endl;
cout << "How many points do the " << bballTeam1 << " have? ";
cin >> score1; //get points
cout << endl;
cout << "How many points do the " << bballTeam2 << " have? ";
cin >> score2; //get points
cout << endl;
winner = scoreCheck(score1, score2); // go to function
if(winner == 1) { //if statements to determine correct output
cout << "The " << bballTeam1 << " are winning!" << endl;
}
else if(winner == 2) {
cout << "The " << bballTeam2 << " are winning!" << endl;
}
else {
cout << "Looks like they are tied up!" << endl;
}
return 0;
}
int scoreCheck(int a, int b) { //a is score1, b is score2
int winner; //set value to int for output
if (a > b) {
winner = 1; //1 is team 1
}
else if(a < b) {
winner = 2; //2 is team 2
}
else if(a == b) {
winner = 0; //0 is tie
}
return winner; //returns value of winner
}
When sitting down to write a function, one of the first things to think about is the best interface for the function: what values it will take, and what will it return.
Some factors to consider here are the purpose of the function, the available inputs, and how the function will be used.
In your case you have created a function which takes two integers as input, performs some very simple logic on them, and returns another integer which is coded with special values to represent the outcome. While this is valid and works, it is awkward in the use case you are putting it to: immediately after calling the function you need to use very similar logic to act on the result.
I would be more inclined to make the function return a string which represents the outcome of the score check, like this:
string scoreCheck(int score1, string team1, int score2, string team2) {
string result;
if (score1 > score2) {
result = "The "+team1+" are winning!";
}
else if(score1 < score2) {
result = "The "+team2+" are winning!";
}
else {
result = "Looks like they are tied up!";
}
return result;
}
Then, you could simplify your main function, replacing all the if/then branches with this:
cout << scoreCheck(score1, bballTeam1, score2, bballTeam2) << endl;
It all boils down to how the function will be used - in this case what we want from the function is a string representing the result of the game which we can directly output. The function is not being used in any other contexts in the program, so we should make it fit this use case as well as possible.
Also note that I changed the last part of the nested if to a plain 'else' - there was no need to check that score1 == score2 since we had already eliminated the other cases.

Creating a structure and calling functions for multiple user inputs, and passing this through the structure to display the information

I must create a C++ program that asks the user to input different products information. So I created a structure to organize the members for the products, and I must use 3 functions, 1 to ask the user for their input, 1 to display the input, and 1 to display the last member Count for every Product item.
My code:
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
struct Product //Structure
{
char Name[25]; //Product Name
char Type[25]; //Product Type
char Exp_Date[25]; //Product Expiration Date
double Price; //Product Price
double Discount_Percentage; //Product Discount Percentage
int Count; //Product Count in stock.
};
//Function Prototypes
Product Receive_Product_Information(Product);
void Display_All_Product_Information(Product & item);
void Display_Each_Product_Count(Product & item);
int main()
{
Product Item[2];
for (int i = 0; i < 2; i++)
{
cout << "Enter the product information for the number " << i+1 << "item" << endl;
Product item[2];
Item[i] = Receive_Product_Information(item[2]);
}
cout << "marker" << endl << endl;
for (int i = 0; i < 2; i++)
{
Product item[2];
Display_All_Product_Information(item[i]);
}
for (int i = 0; i < 2; i++)
{
Product item[2];
Display_Each_Product_Count(item[i]);
}
return 0;
}
//Function Definitions
Product Receive_Product_Information(Product item)
{
cout << "Enter Product Name: ";
cin>>item.Name;
cout << "Enter the Product Type: ";
cin>>item.Type;
cout << "Enter the Product Expiration Date: ";
cin>>item.Exp_Date;
cout << "Enter the Product Price: ";
cin >> item.Price;
cout << "Enter the Product Discount Price: ";
cin >> item.Discount_Percentage;
cout << "Enter the Product Count: ";
cin >> item.Count;
cout << endl << endl;
return item;
}
void Display_All_Product_Information(Product &item)
{
cout << "Name: " << item.Name<< endl;
cout << "Type: " << item.Type << endl;
cout << "Exp Date: " << item.Exp_Date << endl;
cout << "Price: $" << item.Price << endl;
cout << "Discount Percentage: " << item.Discount_Percentage << endl;
cout << "Count: " << item.Count << endl;
return ;
}
void Display_Each_Product_Count(Product &item)
{
cout << "Product Count: " << item.Count << endl;
return ;
}
My Problem:
My problem now is that the members Name, Type and Exp_Date are not being displayed as strings (i.e, Apple, Fruit, December) instead I get (##$%%#$%$%#)
I see multiple issues with this code:
for (int i = 1; i <= 2; i++)
This for statement executes a loop, with i set to 1, and 2, on its two iterations, respectively. Let's keep this in mind, while the rest of the loop is examined.
Product item[2];
This declares an array of two Products: item[0] and item[1]
Item[i] = Receive_Product_Information(item[i]);
The first bug here is on the second iteration, this will reference item[2], since i will be 2, see above.
Unfortunately, only item[0] and item[1] exist, this is undefined behavior. item is a two-element array, and in two element array you have element #0 and element #1. Not element #1 and element #2.
This also applies to the Item array too. It's actually worse in Item's case, since it's assigned to. The typical results on most implementations is a corrupted stack, and and a crash.
Product Receive_Product_Information(Product item)
The Receive_Product_information() function receives its argument by value. However, the argument was copied from an as-yet uninitialized locally-scoped object, in the caller's scope. Technically, this is not a 100% bug, but this is considered poor practice. Either the parameter should be passed by reference, or the object's contents should be properly initialized.
Additionally, it seems that passing the Product parameter does not really do anything usefl.Receive_Product_Information() appears to use standard input to initialize the contents of item ... and then immediately return it. So, why did it need it in the first place?
Receive_Product_Information() does not need this parameter at all. It simply needs to construct a new instance of Product by itself, and then return it.
There may or may not be other problems with this code, this is just what I immediately noticed, at first glance.

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

Functions and structures in C++

/*I got stumped within my code. I think classes will be simpler than structures, but the chapter within my book makes me do structures. : / I am currently getting an error message that my function was not matched up for an overloaded function. The book does talk about them, but the examples of overloading functions in the book aren't helping me out. Also the book wants me to enter account numbers and fill in the objects and when they are asked for an account number they should have the opportunity to "QUIT" entering numbers and proceed onto the next part of the program; that whole way of thinking has my brain a bit fried and I was hoping I could get some help. I apologize if the formatting of my code is messy, I tried to reformat it within here so it would all go into the code brackets.
The Error happens at line... 161 at the displayAccounts function. Parameters were different within the top and bottom of the two functions I changed it and it works. I am going to go over different parts and if its correct post the correct code.*/
I figured out exactly the question that I need. I need the "QUIT" loop to be allowed to be followed up within the account numbers. This would allow the user to enter in a 0 at any time when asked to enter an account number and this was what was confusing me the most.
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
void enterAccountsData(BankAccount *accounts);
void computeInterest(BankAccount *accounts);
void displayAccounts(BankAccount *accounts, const int QUIT);
int accountNum; // holds the account number.
double accountBal; // holds the account balance.
double annualInterest; // holds the interest rate.
int term; // holds the term for the accounts.
};
int main()
{
const int MAX_ACCOUNTS = 100; // The maximum number of bank accounts.
const int QUIT = 0; // sentinal value.
int input;
int num = 0;
BankAccount data[MAX_ACCOUNTS];
BankAccount display;
cout << "Enter " << QUIT << " to stop, otherwise enter 1 and procreed.";
cin >> input;
while(true)
{
if(input != QUIT)
{
data[MAX_ACCOUNTS].enterAccountsData(data);
data[MAX_ACCOUNTS].computeInterest(data);
}
else
{
break;
}
}
display.displayAccounts(data, QUIT);
//system("pause");
return 0;
}
void BankAccount::enterAccountsData(BankAccount *accounts)
{
cout << setprecision(2) << fixed;
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts. (change the number for more bank accounts)
int found;
int quit = 0;
/* First for loop which asks and holds the account information
entered in by the user. */
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
do
{
found = 0;
cout << "Enter in account # " << (num + 1) << endl;
cin >> accounts[num].accountNum; // holds the value of the account number
// Checks if the account number is valid.
while(accounts[num].accountNum < 999 || accounts[num].accountNum > 10000)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[num].accountNum;
}
// Checks if the account numbers are the same.
for(int check = 0; check < num; check++)
{
while(accounts[num].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found); // end of do while.
// Holds the values for the account balances.
cout << "Enter the accounts balance." << endl;
cin >> accounts[num].accountBal;
// Makes sure that the account balance is not negative.
while(accounts[num].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[num].accountBal;
}
// Holds the interest rate.
cout << endl << "Enter the interest rate for account # " << (num + 1) << endl;
cin >> accounts[num].annualInterest;
// Makes sure the interest rate is valid
while(accounts[num].annualInterest > 0 && accounts[num].annualInterest > 0.15)
{
cout << endl << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[num].annualInterest;
}
// Makes sure the interest rate is not negetive
while(accounts[num].annualInterest < 0)
{
cout << endl << "Interest rate cannot be negetive" << endl;
cin >> accounts[num].annualInterest;
}
// Holds the value for the length of the interest.
cout << endl << "How many years will this interest rate be held for? " << endl;
cin >> accounts[num].term;
//Checks for valid length of time for the term held
while(accounts[num].term < 0 || accounts[num].term > 11)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[num].term;
}
}
cout << "If you wish to stop enter 0 otherwise type 1 to proceed" << endl;
cin >> quit;
if(quit = 0)
{
return;
}
}
void BankAccount :: computeInterest(BankAccount *accounts)
{
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts.
const int MONTHS_IN_YEAR = 12;
double total = 0;
double average = 0;
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
/*Goes through the term year and calculates the total
of each account balance. Then calculates the average. */
for(int year = 0; year < accounts[num].term; year++)
{
for(int month = 0; month < MONTHS_IN_YEAR; month++)
{
accounts[num].accountBal = (accounts[num].accountBal * accounts[num].annualInterest) + accounts[num].accountBal;
}
int month = 1;
cout << endl << "Total amount for account # " << (num + 1) << " is: " << accounts[num].accountBal << endl ;
total += accounts[num].accountBal;
cout << endl << "The total amount of all accounts is: " << total << endl;
}
}
average = total / NUM_OF_ACCOUNTS;
cout << "Average of all the bank accounts is: " << average << endl;
}
void BankAccount :: displayAccounts(BankAccount *accounts)
{
int input = 0;
int found;
const int MAX_ACCOUNTS = 100;
int quit = 0;
cout << endl << "Which account do you want to access?" << endl <<
"To stop or look at none of the account numbers type: " << quit << endl;
cin >> input;
for(int num = 0; num < MAX_ACCOUNTS; num++)
{
while(num < MAX_ACCOUNTS && input != accounts[num].accountNum)
{
num++;
}
if(input == accounts[num].accountNum) // This if sees if an account matches what the user entered.
{
cout << "Account: " << accounts[num].accountNum << endl << "Balance is: " <<
accounts[num].accountBal << endl << "Interest rate is: " << accounts[num].annualInterest;
cout << endl << "Enter another account number or type 0 to quit." << endl;
found = 1;
cout << endl;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number." << endl;
cin >> input;
}
}
}
In C++, classes and structs are exactly the same constructs. They are, in fact, one thing — a User-Defined Type.
There is a different that is invoked depending on whether you used the keyword struct or class to define your UDT, and that is that class-key defaults to private member access and private inheritance, whereas struct-key defaults to both being public.
Other than this syntax difference, you can use either without worrying about one being "simpler" than the other.
Anyway, your compiler error (please provide it next time) is probably due to a declaration/definition mismatch.
Your declaration:
void displayAccounts(BankAccount *accounts, const int QUIT);
Start of your definition:
void BankAccount :: displayAccounts(BankAccount *accounts) {
The start of the definition should be
void BankAccount::displayAccounts(BankAccount* accounts, const int QUIT) {
to match. I've also fixed your spacing to be nicer. :)
void displayAccounts(BankAccount *accounts, const int QUIT);
... looks different between declaration and definition. Second parameter is missing in the definition.
Not sure what your question is, but classes and structs in C++ are equivalent except that fields are public by default in structs, but private by default in classes.
In the struct’s displayAccounts() member declaration you have:
void displayAccounts(BankAccount *accounts, const int QUIT);
and when defining the method later:
void BankAccount :: displayAccounts(BankAccount *accounts)
You have just missed
const int QUIT
parameter for the member function definition.