Palindrome

Aug 24, 2016 at 8:43pm
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;

}
Aug 24, 2016 at 9:11pm
Try converting every character to the same case (upper/lower) and then running your test.
Aug 25, 2016 at 5:41pm
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 Aug 25, 2016 at 5:42pm
Aug 25, 2016 at 6:00pm
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
Sep 10, 2016 at 9:13pm
Thank you all very much that helped greatly.
Topic archived. No new replies allowed.