Palindrome Check

Can you please review my program, it reverses the words just fine but I need help with telling the user if it is a palindrome or not. Anything is really appreciated.

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
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
using namespace std;

string compress(string s) 
{
    string result;
    for (int i = 0; i < s.size(); i++)
    {
        if (isalpha(s[i]))
        {
            result += tolower(s[i]);
        }
    }
    return(result);
    
}

string reverse(string s)
{
    string result;

    for (int i = 0; i < s.size(); i++)//in essence this resizes the string so it can hold all the characters
    {
        result += s[s.size() - i - 1];
    }

    return(result);
}

void palindrone(string &compressed, string &reversed) //checks to see if the original word and the reversed word match
{
	
        if (compressed == reversed)
        {
            cout << "It is a palindrome"<<endl;
        }
        else
        {
            cout << "It is not a palindrome"<<endl;
		}
    }


int main()
{
    string input;
    cout << "Enter a sentence to check:"<<endl;
    getline(cin, input); // gets whole line instead of one word

    string compressed = compress(input); //calls the compressed input
    cout << "Compressed input: " << compressed <<endl;

    string reversed = reverse(compressed); //calls the compressed word into reverse
    cout << "Reversed input: " << reversed <<endl;
	
	palindrone; //calls palindrone

	system("pause");
    return (0);
}
palindrone; should be palindrone(compressed, reversed);, shouldn't it?
Some remarks about the code. Function compress can be written as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string compress( const string &s ) 
{
    string result;
    result.reserve( s.size() );

    for ( string::size_type i = 0; i < s.size(); i++)
    {
        if (isalpha(s[i]))
        {
            result += tolower(s[i]);
        }
    }

    return(result);
}


Function reverse is unnecessary because you can use a string constructor instead of the function.
So function palindrone can look as

1
2
3
4
inline bool palindrone( const string &compressed ) 
{
        return ( compressed == string( compressed.rbegin(), compressed.rend() ) );
}


In main there will be the code

1
2
3
4
5
6
7
8
        if ( palindrone( compressed ) )
        {
            cout << "It is a palindrome"<<endl;
        }
        else
        {
            cout << "It is not a palindrome"<<endl;
        }
Last edited on
Topic archived. No new replies allowed.