Validated user input in C++
Inputs have to be validated before allowing any kind of processing or operations to be performed on it. This is extremely important because , an unhandled wrong input might have the complete ability to crash a system. C++ has some good validation techniques that can be used to validate most kind of inputs. This post discusses some of the techniques and its shortcomings and what could be done to improve the quality of validation.
Now, consider a program has to accept only integer inputs and reject all the others. So, the developer would have declared to store the integer value in say “int a;”. So “a” will store the input value.
When the user input is accepted using the “cin>>a” statement, we can use the inbuilt methods surrounding the “cin” statement to test its status.
Here is a sample program: –
#include
#include
using namespace std;
int main()
{
int a;
coutcin>>a;
while(1)
{
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits
coutcin>>a;
}
if(!cin.fail())
break;
}
coutreturn 0;
}
#mastery27 #TC1017 by Mitzi Hernandez is licensed under a Creative Commons Attribution 4.0 International License.