Palindromes and Reversing Strings

I'm kind of curious as to how to have a program recognize a palindrome. Like if someone entered a word, the program could tell them whether or not it is a palindrome. Or if a program could take an inputted word and reverse it. Anyone know how these would work?
If you are allowed to use std::string then it is being done simply. For example

1
2
3
4
std::string s( "123454321" );

bool polindrome = s == std::string( s.rbegin(), s.rend() );
std::cout << "Word " << s << " is " << ( polindrome ? "" : "not " ) << "a polindrome\n";


Also you can read the reference with name "Basic Palindrome vector"

http://cpp.forum24.ru/?1-1-0-00000012-000-0-0-1352733173
with a similar question.
Last edited on
Okay that was really helpful, thanks! I got a function to work for the determining palindrome, and I got one to work for reversing a string, but I want to have an option to select one or the other, and the if statements I used don't seem to work. If I add the if statements, the program no longer gets input, and just prints that " is a palindrome." What am I doing wrong??

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream> 
#include <vector> 
#include <string> 
#include <cctype>
  
using namespace std; 

bool determine_palindrome(const string&);

int main(int argc, char *argv[]) {
    
	cout << "Would you like to check for a palindrome, or reverse a string? (Enter 1 for palindrome, 2 for reverse string: ";
	int pickfunc;
	cin >> pickfunc;
	
	if (pickfunc == 1){
	
		string line;

		cout << "Enter word: ";
		getline(cin,line);
		cout << line << " is ";
		if (determine_palindrome(line) == false) cout << "not ";
		cout << "a palindrome." << endl;
		return 0;
	}
	
	if (pickfunc == 2){
	 	string words; 
  
		cout <<"Enter words : " ; 
		getline( cin,words ); 
	  
		string reverse_string( words.rbegin() , words.rend() ); 
		cout << "\nBackwards , it's : " << reverse_string << endl << endl;
	}
}

bool determine_palindrome(const string &s) {
    bool pal = true;
    const char *p = s.c_str();
    const char *q = p + s.size() - 1;

    while ((p < q) && (pal == true)) {
        pal = (tolower(*p++) == tolower(*q--));
    }
    return pal;
}
I think the problem is that after the statement

cin >> pickfunc;

the new line character that corresponds to pressed ENTER key is still in the input buffer. So the next getline function reads an empty string that is it reads until that new line character.

Interesting. Do you know how I can fix it?
You can read here

http://cplusplus.com/forum/beginner/1988/

or use a simple construction

std::cin.ignore( 1, '\n' );

after the statement

cin >> pickfunc;
Okay great that worked perfectly thank you!
Topic archived. No new replies allowed.