I succeeded in the first part of the exercise, this attempt is the second part. I am not sure I have accomplished the goal, and would appreciate the input of more knowledgeable minds. As always, critiques of my techniques welcome.
This is an exercise from the book titled 'Beginning C++ through Game Programming' by Michael Dawson.
Challenge me, despite my novice level of understanding.
The exercise:
Using default arguments, write a function that asks the user for a number and returns that number. The function should accept a string prompt from the calling code. If the caller doesn't supply a string for the prompt, the function should use a generic prompt.
Next, using function overloading, write a function that achieves the same results.
My code:
// Chapter 05, Exercise 03: Beginning C++ through Game Programming
/* Using default arguments, write a function that asks the user for a
number and returns that number. The function should accept a string
prompt from the calling code. If the caller doesn't supply a string
for the prompt, the function should use a generic prompt.
Next, using function overloading, write a function that achieves
the same results.
*/
#include <iostream>
#include <string>
int askNumberFn(int number, std::string prompt = "Please enter a number, now: "); // default arguments must come last, in order of excecution
std::string askNumberFn(std::string prompt = "Please type a number, now: "); // default parameters must be different in order to overload Fn
char exitTimeFn();
int main()
{
askNumberFn("Please type a number: "); // We require the calling code to return a prompt
askNumberFn(); // We also require the Fn to return a default prompt
int number = 0;
number = askNumberFn(number, "Please enter a number: "); // To prove we have overloaded the FN, we require the Fn to also return an int
number = 0; // We return the value of number to zero, in order to remove any doubt, if we input the same number again
number = askNumberFn(number); // Lastly, we have to prove our overloaded Fn displays a default prompt
exitTimeFn();
return 0;
}
int askNumberFn(int number, std::string prompt)
{
std::cout << prompt;
std::cin >> number;
std::cout << "You entered the number: " << number << std::endl;
return number;
}
std::string askNumberFn(std::string prompt)
{
std::string word;
std::cout << prompt;
std::cin >> word;
std::cout << "You typed the number: " << word << std::endl;
return word;
}
char exitTimeFn()
{
char exitNow;
std::cout << "Press 'x' to exit: ";
std::cin >> exitNow;
return exitNow;
}