So basically there are two functions that you should be concerned about:
Read and ReadNoVal.
Read takes a number of arguments and comes in several flavors.
Now, here is the general structure of how the function works:
- Print question.
- Retrieve input.
- Convert input to appropriate data type.
- If fail, print error message, goto beginning.
- Verify input by calling verification function.
- If verification function returns false, print error message, goto beginning.
- Everything works and the function returns.
Essentially, you call the function once to get some valid input. When the function returns, you have a valid input.
The argument the read function takes are:
- Reference to the variable to hold the input data.
- A string that contains the questions to print out before getting input.
- A string to print if the input cannot be converted into appropriate type.
- A string to print if the input doesn't pass the verification.
- A validator functor.
The strings can be of any type that can be printed. It can be std::string, const char*, etc. So long as they can be passed to std::cout or std::wcout. This opens up possibilities for your own string types, or boost's string types.
The validator function is a pointer to a function or a functor that returns a bool and accepts a reference to the converted input. It shall return true if the data is valid; false otherwise.
Note that the strings for valid inputs can be omitted, in which case, "Invalid input!" will be printed instead.
ReadNoVal is the same as Read, except it does not take a validation function. So that means if the input can be converted into the proper data type, the function returns.
The data type to convert to is determined by the type of the variable to hold the answer.
So, for example, say that we want an integer in the range of 100 - 200. We could write:
Code:
int Num;
Stuff::Input::Read(Num, "Enter a number between 100 and 200: ", "That is not a number!",
"The number must be within the range 100 - 200!",
[](int Number) -> bool { return Number >= 100 && Number <= 200; });
Assuming I haven't made any mistakes, this should compile.