The teacher's wording translates into this:
#include <string>
#include <iostream>
#include <stdexcept>
/**
* Prompts the user for an integer input on standard input, and
* returns it. The prompt text is #prompt_text, or "Enter input please"
* if not given.
*
* @throws std::runtime_error if input is not an integer
*/
int promptForInput(const std::string& prompt_text = "Enter input please")
{
std::cout << prompt_text << ": " << std::flush;
int result;
if (std::cin >> result)
return result;
else
throw std::runtime_error("Could not understand your input");
}
int main()
{
const int x = promptForInput();
std::cout << "You entered: " << x << std::endl;
const int y = promptForInput("Gimme intz lol");
std::cout << "You entered: " << y << std::endl;
}
With overloading rather than default arguments, the function is like this:
/**
* Prompts the user for an integer input on standard input, and
* returns it. The prompt text is #prompt_text.
*
* @throws std::runtime_error if input is not an integer
*/
int promptForInput(const std::string& prompt_text)
{
std::cout << prompt_text << ": " << std::flush;
int result;
if (std::cin >> result)
return result;
else
throw std::runtime_error("Could not understand your input");
}
/**
* Prompts the user for an integer input on standard input, and
* returns it. The prompt text is "Enter input please".
*
* @throws std::runtime_error if input is not an integer
*/
int promptForInput()
{
return promptForInput("Enter input please");
}
In both cases, the output of this program is like this:
[tomalak@andromeda ~]$ ./test2
Enter input please: 4
You entered: 4
Gimme intz lol: 62
You entered: 62
If you enter a non-integer, you'll get a non-descript process error instead:
[tomalak@andromeda ~]$ ./test2
Enter input please: lol
terminate called after throwing an instance of 'std::runtime_error'
what(): Could not understand your input
Aborted (core dumped)
(N.B. I recommend a try
/catch
situation in main
, but I couldn't be bothered.)
But after talking with my teacher, he explained that with the program a user should be able to enter and int 5 or a string "five", and the program should be able to determine if it is an int or string and output it.
I can't imagine that this is right; it seems pointless, and it has nothing to do with the quoted assignment. I believe you misunderstood this conversation.