Code Dump

Feb 9, 2013 at 10:33am
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 Feb 9, 2013 at 10:33am
Feb 9, 2013 at 12:30pm
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 Feb 9, 2013 at 12:31pm
Feb 9, 2013 at 3:00pm
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.