I'm writing a simple program that can check for words or phrases and determines if it is a Palindrome or not. A palindrome is a word or phrase that reads the same backward as forward. Here are some examples of palindromes:
Radar (can read it backward or forward)
Madam!I'm adam
Unfortunately, everything I input came out as "It is not a palindrome", I'm not sure what I did wrong as I followed step by step very closely as in the guild line:
1. Create a string variable
2. Convert the string to uppercase characters
3. Keep only the alphabetic characters.
4. Compare the first character with the last character. If they're are the same, compare the next character.
Can someone please check my codes and tell me what wrong with it, thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
char str[80], again;
int strlength, i,j=0;
int front=0,back; int flag=1;
gets(str);
do {
cout << "Input a string: ";
cin >> str;
//Get the length of string str
strlength = strlen(str);
//Convert all the characters in the string str to uppercase
for(int i = 0; i < strlength; i++)
{
str[i] = toupper(str[i]);
}
//Remove all the special characters except letters a - z
for(int j = 0; j < strlength; j++)
{
if (isalpha(str[i]))
{str[j] = str[i];
j++;
}
}
str[j]= '\0';
//front index is pointed to the first character in the string str
front = 0;
//back index points to the last character in the string str
back = strlength - 1;
//Compare the first character with the last character. If they're are the same,
//compare the next character.
for(int i=0; i< strlength/2;i++)
{
if(str[front] != str[back])
{
flag = 0;
break;
}
front++;
back=back -1;
}
if(flag == 0)
cout<<"It is not a palindrome"<<endl;
else
cout<<"It's a palindrome"<<endl;
//Do-While loop until user exit
cout <<"Input another string (y/n)?";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}
|