View Full Version: String input validation

C++ Learning Community > C++ in General > String input validation


Title: String input validation
Description: C++ - Palindrome


Emefa - March 12, 2004 12:21 AM (GMT)
Hi
I am writing this palindrome program that is giving me a whole lot of problems. One part is palindrome and the other part is supposed to be Data validation.
The Palindrome is working fine but I can not get the data validation part.
CODE

#include<iostream>

using std::cout;
using std::cin;
using std::endl;



int pal(char [],int l);

int main()

{



int n=50;
int n1=50;      
char string[50];
char string1[50];

cout<<"enter a word...: ";
cin.getline(string,n);
             
n=strlen(string);
for (int i=0; i<n;i++){

string1[i]=string[i];  
                           //insert j to add only good characters

}

n1=strlen(string1);
//printing forward
for (i=0; string[i]!='\0'; i++)
cout<<string[i]<<endl;

                                          //Printing backward
cout<<endl<<endl;
for (i=0; i<n; i++)
cout<<string[(n-i)-1]<<endl;

cout<< "Guess what!!!";

int t;
                    //function return a number that is test to output the proper
t= pal(string, n);
//testing the boolean number returned from the pal function
if(t==1)
cout<<" Yes!! This is a palendrome"<<endl;
else
cout<<" No!! This is not a palendrome"<<endl;

return 0;

}

int pal(char Mystring[], int l)

{
                          //checking if it is a pal....

int i;
       
for(i=0; i<l; i++)//loop to read the characters of the entered charatcetr array
if (Mystring[i]!=Mystring[(l-i)-1])//in the loop comparing characters in inverse order

{

return 2;          

}

//cout<<"YEEEEH it is a Palindrome"<<endl;

//cout<<"Sorry it is not a Palindrome"<<endl;

return 1;

}


How can I validate that input characters take out white spaces or make sure that there should be an input at the beginning of the program before it allows the palindrome to start working?

Thanks,
- Emefa

C-Man - March 12, 2004 06:17 AM (GMT)
Take out spaces and useless charaters by saing
CODE


BOOL valid(char c) // returns true if charater is alpha / numeric
{
if((!isalpha(c))||(!isdigit(c)))
  { return FALSE; }
 else
  { return TRUE; }

}

...

if(string[0] == 0){ // no input } else { // is input }
 
...

int n = 0;
for (int i=0; i<n;i++){
if(valid(string[i])){
string1[n++]=string[i];  
}
                         
}



had'nt tested it yet but should work :mellow: .




* Hosted for free by InvisionFree