#include<iostream> //Preprocessor commands
#include<string>
#include<cmath>
#include<cstdlib>
using namespace std; //Location of library
int input_val(); //Function to validate input
int main()
{
char ch;
cout<<" ***Example 9.3 - Input Validation***"<<endl<<endl;
cout<<"The user entered a valid integer data type = "<<input_val()<<endl<<endl;
cout<<"Enter 'e' to exit... "; //Hold screen for viewing
cin>>ch;
return 0; //End of program.
}
int input_val()
{
/*Validation criterion
1. The string must not be empty.
2. A "+" sign may or may not be the first character (not a "-" sign).
3. If a sign is present, at least one digit must follow that sign.
4. Scientific, exponential or engineering notation is NOT allowed.
5. No characters or blanks may exist in the string other than the ones mentioned above.
*/
string text;
int x = 99, i, d;
while (x != 0)
{
try
{
//Initialize decimal counter;
d = 0;
cout<<"Enter a valid integer data type: ";
getline(cin,text);
//Check for zero length
if (text.length() == 0) throw 1;
//Check first character
if ( !isdigit(text.at(0)) && !(text.at(0) == '+') ) throw 2;
//Check for leading +/- without a following digit
if ( ( text.at(0) == '+')&& text.length()<2 ) throw 2;
//Check remainder of string for digits (or one decimal point)
for (i = 1; i <text.length(); i++) if (!isdigit(text.at(i))) throw 3;
//Reset while sentinel
x = 0;
}
catch (int x)
{
if (x == 1) cout<<" Entry error...empty string!"<<endl<<" Try again... ";
if (x == 2) cout<<" Entry error...first digit error!"<<endl<<" Try again... ";
if (x == 3) cout<<" Entry error...not all digits!"<<endl<<" Try again... ";
//Reset sentinel
x = 99;
}
}
return atoi(text.c_str());
}
I'm trying to use this function. Basically, once it goes through all that validation, I need to get the number and store that number into an array. I can never get it working. What am I suppose to do?