.

Thursday 22 January 2015

How to Validate a Number/Integer in c++ ?

Validation of integer in c++ involves three steps -

1) Declare the function inside the body of a class.

2) Give definition to it outside the class using scope resolution.

3) Call it using do while loop by passing string type of number in it.


Function declaration -

class Validate
{
......
bool validateLongNumber(string );
...

}

Function Definition (outside the class) -


bool Validate::validateLongNumber(string &str_string)
{
if(str_string.length()<1||str_string==" ")
{
cout<<"Field Cannot be Blank"<<endl;
return 0;
}

int i;
do
{
for(i=0;i<str_string.length();i++)
{
                                if(str_string[0]==' ')
                                {
                                cout<<"Input cannot begin with a blank"<<endl;
                                return false;
                                }

if(atol(str_string.c_str()))
{
if(!isdigit(str_string[i]))
{
cout<<"Enter valid number\n"<<endl;
return 0;
}
else continue;
}
if(str_string[0]=='0')            
{
                      cout<<"Please Don't Enter '0'"<<endl;
       return false;
                        }

cout<<"Enter valid number\n"<<endl;
return 0;

}
return 1;

}while(i!=str_string.length());
}


Function calling -
string number;

do
{
cout << "Enter the Number"<<endl;
        getline(cin,number);
}while(Validate::validateLongNumber(number)!=1);

No comments:

Post a Comment