I am starting to program in C ++ and have to do a lot of input validation. I found this feature that seems to be universally applicable, but I am having problems with one aspect; If I typed -90, the program did not give an error. my question (s): 1. How can I add the fact that the input cannot be & lt = 0? 2. Is there a better way to limit user input? Maybe a library in C ++?
Thanks for any help or advice.
#include <ios> // Provides ios_base::failure
#include <iostream> // Provides cin
template <typename T>
T getValidatedInput()
{
T result;
cin >> result;
if (cin.fail() || cin.get() != '\n')
{
cin.clear();
while (cin.get() != '\n')
;
throw ios_base::failure("Invalid input.");
}
return result;
}
Using
inputtest.cpp
#include <cstdlib> // Provides EXIT_SUCCESS
#include <iostream> // Provides cout, cerr, endl
#include "input.h"
int main()
{
using namespace std;
int input;
while (true)
{
cout << "Enter an integer: ";
try
{
input = getValidatedInput<int>();
}
catch (exception e)
{
cerr << e.what() << endl;
continue;
}
break;
}
cout << "You entered: " << input << endl;
return EXIT_SUCCESS;
}
source
share