Code Dump

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
#include "palindrome.h"

void CPali::input()
{
	cout << "Word: ";
	cin >> word;
}

void CPali::check()
{	
	length = word.size()-1;

	for (int i = 0; i < length; i++)
	{
		if(word[i] == ' ')
		{
			word.erase(word[i],1);
			length = word.size()-1;
		}
	}

	for (int i = 0, p = length; p > i; i++, p--)
	{
		if (toupper(word[i]) == toupper(word[p]))
		{
			
			valid = true;
			
		}
		else if (toupper(word[i]) != toupper(word[p]))
		{
			valid = false;
		}

	}

	if (valid)
	{
		cout << "Its a palindrome!" << endl;
	}
	else
	{
		cout << "It's not a palindrome..." << endl;
	}

};
Last edited on
It is not a good approach. I think that function check shall not modify member word and shall have return type bool. I would declare it as

bool IsPalindrome() const;
Last edited on
You have a problem with your loop at line 22.

valid is not tracking it's previous state. When you exit out of the loop, valid only has the state of the last comparison, not the state of all comparison upto and including the last. Line 22-25 should look like this:
1
2
3
4
5
6
7
    valid = true;  // Assume it's a palindrome to start
    for (int i = 0, p = length; p > i; i++, p--)
    {   if (toupper(word[i]) != toupper(word[p]))
        {   valid = false;
             break;   // no point in checking any further
         }
    }
Topic archived. No new replies allowed.