This week in class we are looking at functions and how to use them.
This is the example we got during class:
#include <iostream>
#include <string>
using namespace std;
//function prototype
int getTotal(int,string);
void verifySeasons (int&);
int main()
{
string name; // name of player
int totalGoals = 0; // total goals for all seasons
int totalAssists = 0; // total assists for all seasons
int seasons = 0; // number of seasons played
char next = 'y';
do
{ // start of do-while
// Have the user input the player's name
cout << "Enter the player's name: ";
getline(cin, name);
// Have the user input the number of seasons
cout << "Enter number of seasons: ";
cin >> seasons;
//call the verifySeasons() function
verifySeasons (seasons);
// call the getTotal() function
totalGoals = getTotal(seasons, "goals");
totalAssists = getTotal(seasons, "assists");
// Use a for loop to input goals and assists for each season
cout << endl << endl;
cout << "Name: " << name << endl;
cout << "Total Goals: " << totalGoals << endl;
cout << "Total Assists: " << totalAssists << endl;
cout << "Total Points: " << totalGoals+totalAssists << endl;
cout << "Keep going? (y/n): " << endl;
cin >> next;
// reset totals
totalGoals = 0;
totalAssists = 0;
cin.ignore(10, '\n'); // clear out input buffer
} while (next == 'y' || next == 'Y'); // end of do-while
system("pause");
return 0;
}
int getTotal (int numSeasons, string whichone)
{
int data = 0;
int total = 0;
for (int count = 1; count <= numSeasons; count++)
{
// Input goals for a season and update goal total
cout << "Enter " << whichone << " for season #" << count << ": ";
cin >> data;
total = total + data;
}
return total;
}
void verifySeasons (int& numSeasons)
{
while (numSeasons <= 0)
{
cout << "Seasons must be positive - Try again" << endl;
cout << "Enter number of seasons: ";
cin >> numSeasons;
}
}
Basically, takes inputs of a player stats and adds them.
I understand the general concept, however what I don't quite get is how to properly call in the function.
#include <string>
using namespace std;
//function prototype
int getTotal(int,string);
void verifySeasons (int&);
int main()
Why is "getTotal" int, and verifySeasons void?
Another question I have is what's in the parenthesis.
Why "int, string" for getTotal, and "int&" for verifySeasons?
Thanks for your help!!