I made a program to find if a entered string is palindrome or not palindrome but it always says that its not a palindrome
#include
#include
To give you a clue I've done some tidier indenting of a bit of your code:
for(i=0;i<halflen;i++)
{
if(str[i]!=str[i+halflen])
flag=0;
break;
}
A C
-flavored solution : )
bool is_palindrome(const char* s) {
const char* p = s;
while (*p != '\0') ++p;
while (s < p) if (*s++ != *--p) return false;
return true;
}
bool isPalindrome(char* str) {
char* s = str;
char* e = str;
while(*e) e++;
--e;
while(s < e) {
if(*s != *e) return false;
++s; --e;
}
return true;
}
Here you want something like...
if(str[i]!=str[strlen (str) - i - 1])
{
flag = 0;
break;
}
The break
needs to go in the if
block otherwise it will always get executed. Initialising flag
at some point would be a good idea, too. If I might be permitted an observation, ALWAYS enclose the if-block and else block in curly brackets even if there is only one statement; it would save you several of the problems you've got here.
Later - edited per Mr Rodriguez' comments below.
Here is a better way.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter your text: ";
cin >> input;
transform(input.begin(), input.end(), input.begin(), ::tolower);
if (input[0] == input[input.length()-1])
cout << "Palindrome";
else
cout << "not palinrome";
cin.ignore();
cin.get();
}
From the 2005 version of myself:
bool isAlphaNumeric(char c)
{
return (iswalpha(c) || iswdigit(c));
}
bool isPalindrome(char *str)
{
/* A man, a plan, Anal Panama!!! */
if(*str == '\0')
{
return false;
}
int len = strlen(str);
if(len <= 1) return true;
char *start = str;
char *end = start + len - 1;
while(start < end)
{
if(!isAlphaNumeric(*start))
{
*start++;
continue;
}
if(!isAlphaNumeric(*end))
{
*end--;
continue;
}
if(towlower(*start) != towlower(*end))
{
return false;
}
*start++;
*end--;
}
return true;
}