Palindrome

OK, what I have got so far works well enough, but it will not ignore capitalization. What do I do?

#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main()

{

cout << "Please Enter The Suspected Palindrome:";

string s;

cin >> s;

if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )

cout << "This is a palindrome.";

else

cout << "This is not a palindrome.";

cout << "\n\n";

system ("pause");

return 0;

}
Try converting every character to the same case (upper/lower) and then running your test.
greengirl1968

Add this bit of code that I found and it should solve your problem.

1
2
3
4
5
6
7
#include <locale> // heder file to use the loc variable

locale loc;
for (int lp = 0; lp < s.length(); lp++)
{
	s[lp] = tolower(s[lp], loc);
}


Not that I know many palindromes to test this with, but it did work.

Hope that helps

Andy

PS
Forgot to mention this should go after the cin and before the if statement.
Last edited on
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
#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <iomanip>

std::string sanitise( const std::string& str ) // remove non-alphanumeric, convert to all lower case
{
    std::string result ;
    for( char c : str ) if( std::isalnum(c) ) result += std::tolower(c) ;
    return result ;
}

int main()
{
    std::cout << "Please Enter The Suspected Palindrome: ";

    std::string str ;
    std::getline( std::cin, str ) ;

    std::cout << "\nThe string " << std::quoted(str) << " is " ;

    str = sanitise(str) ;
    if( std::equal( str.begin(), str.begin() + str.size()/2, str.rbegin() ) ) std::cout << "a palindrome.\n";
    else std::cout << "is not a palindrome.\n";
}

http://coliru.stacked-crooked.com/a/b5c98c1e805f78d7
Thank you all very much that helped greatly.
Topic archived. No new replies allowed.