I am new to programming and have been having a lot of trouble with user input validation. Everything I found online I could break and I finally put this function together that appears to be unbreakable. It is for int
and double
specifically.
I am curious about how it might be critiqued by experienced programmers. How did I do? What can be improved? What are some issues I might run into? One issue I ran into was when I #include<Windows.h>
, max()
becomes an issue in this code, so I had to use #define NOMINMAX
. I wonder if there is a way around that as well. I am using this code with Visual C++ in Visual Studio.
#include<iostream>
#include<string>
#include<limits>
using namespace std;
template<class T>
void input(T& input, int low, int high, string message)
{
input = low - 1;
while (input < low || input > high)
{
cout << message;
while ((cin >> input).fail() || cin.peek() != '\n')
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << message;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
T
isstd::string
?std::array
?MyClass
? If you want to support multiple return types, I advise for overloading + factoring the common code into a separate helper function. \$\endgroup\$low - 1
isn't available, there will be a (nowadays reasonably understandable) compile time error. Templates are not a boogeyman \$\endgroup\$template<class T> void input(T& input, int low, int high, string message) ...
toauto input = [](auto& input, auto low, auto high, string message) ...
\$\endgroup\$