.

Thursday 22 January 2015

How to Validate String in c++ ?

Validation of string 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  in it.

Function Declaration-

class Validate{
......

bool validateString(string&);

.....
}

Function Definition (outside class) -

bool Validate::validateString(string& str_string)
{
if(str_string.length()<1||str_string==" ")
                {
                cout<<"Field Cannot be Blank"<<endl;
                return 0;
                }
 
int i;
do
{
                                if(str_string[0]==' ')
                                {
                                cout<<"Input cannot begin with a blank"<<endl;
                                return false;
                                }

for(i=0;i<str_string.length();i++)
      {
if(!(isalnum(str_string[i])||str_string[i]=='.'||isspace(str_string[i])||str_string[i]=='-'))
{
cout<<"Enter valid string:\n"<<endl;
    return 0;
}
    }

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



Function Call-
string name;
do
{
cout <<"Enter the Name:"<<endl;
getline(cin,name);
}while(Validate::validateString(name)!=1);
}

No comments:

Post a Comment