For some reason whenever I enter the word "Rotor" on the first time it detects it as a palindrome just fine. But when I try the word for the third time it says it isnt anymore?
#include <iostream>
#include <string.h>
usingnamespace std;
int main(){
char string1[20], repeat('y');
int i, length;
int flag = 0;
do {
cout << "Enter a string: ";
cin >> string1;
length = strlen(string1);
for(i=0;i < length ;i++){
if(tolower(string1[i]) != tolower(string1[length-i-1])){
flag = 1;
break;
}
}
if (flag) {
cout << string1 << " is Not a Palindrome\n" << endl;
}
else {
cout << string1 << " is a Palindrome\n" << endl;
}
cout << "Try again [Y]es [N]o > ";
cin >> repeat;
cout << endl;
} while (tolower(repeat) == 'y');
return 0;
}
when I execute it looks like this:
Enter a string: maam
maam is a Palindrome
Try again [Y]es [N]o > Y
Enter a string: test
test is Not a Palindrome
Try again [Y]es [N]o > y
Enter a string: Rotor
Rotor is Not a Palindrome
Try again [Y]es [N]o > n
but when "Rotor" come first it looks like this:
Enter a string: Rotor
Rotor is a Palindrome
Try again [Y]es [N]o > n
Its fine, for an odd 5 long string its doing this:
[0] ==[4]
[1] ==[3]
[2] ==[2]
[3] ==[1]
[4] ==[0]
and for even 4 length
[0] ==[3]
[1] ==[2]
[2] ==[1]
[3] ==[0]
which works but checking to i = length/2 is better, as it does half the work and ignores the middle letter for odd lengths due to int division.
Fair warning, mixing getline with operator>> will cause input weirdness to happen. std::istream::operator>> doesn't remove the endline character ('\n') (or specified delimiter) from the input stream, getline does remove the endline character.
The tolower() and the other c type functions take an arg of int. When passing a arg of type char then this should be cast to unsigned char. Also for those functions that return a value other than bool, this is again an int which should be cast to char.