PDA

View Full Version : C++ Palindrome Problem


XemMeg
06-30-2010, 12:45 AM
Hello!

I've been working on creating a program which detects if the string the user entered is a palindrome.
For some reason, my program doesn't seem to be looping. My methodology was to compare the first letter to the last letter, 2nd to first to the 2nd to last, etc.
If they all matched up, then it's a palindrome.
Here is the code below:

#include <iostream>
#include <string>
using namespace std;

void main() {
char phrase[85];
bool palindrome;
int length;
int count = 0;

cout << "Enter a phrase: ";
cin.getline (phrase, 84);
length = strlen (phrase);

for (count = 0; count != length / 2.0; count++) {
int end = length - count;
if (phrase[count] == phrase [end]) {
cout << "This is a palindrome!";
}
else {
break;
}
}

}

Iplayed around with cout to figure out what was going wrong...The program can cout phrase [count], but not phrase [end]. I'm puzzled as to why this is. I would appreciate someone's suggestions or help.

abduraooft
06-30-2010, 08:25 AM
The program can cout phrase [count], but not phrase [end]. I'm puzzled as to why this is. I would appreciate someone's suggestions or help.
int end = length - count;
strlen() returns the total number of characters(excluding the 'null' at the end) present in the string, where as array starts its indexing from 0. Thus, say, if there's a string str[], which returns 5 as its string-length, str[5] won't be the last character as you expected.
if (phrase[count] == phrase [end]) {
cout << "This is a palindrome!";
}
The above line would print that string whenever it finds a match.

You'd need to iterate through the string and set a flag (and break; ), when ever a mismatch occurs and then check the value of that flag (from outside the loop) to print the result.

ruhallah
10-10-2010, 08:26 AM
by using the reverse(v.begin(),v.end()) or by using strrev, string reversed.now only by checking the character by character the string only til the middle of string. now your answer is ture.

sophieben
10-15-2010, 08:41 AM
Instead of Phrase[end] you should use phrase[84].

solarpowerlight
10-16-2010, 08:24 AM
There is much easier way to check the string if it is palindrome or not.
Use two variables in the program. The first variable will contain the original string. The second variable will contain the value of var=strrev(string) function reverse the string. After that, compare the two variables by using strcmp(str1,str2) to check if they are the same.

Hope this helps.