Palindrome prog, removing whitespace

I have an assignment where i have to make a palindrome program. As you can see i have already done the basic palindrome prog, however i am now stuck since the program goes into a infinite loop whenever a word with whitespaces is added.

I have also tried searching for methods online however they do not seem to work for me...

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
void CPali::check()
{
	length = strlen(palin);
	
	for (int i = 0, p = length-1; p>i; i++, p--)
	{
		if (palin[i] == ' ')
		{
			palin[i] = palin[i+1];
			palin[p] = palin[p+1]; 
		}
		

		if (toupper(palin[i]) == toupper(palin[p]))
		{
			
			valid = true;
			
		}
		else
		{
			valid = false;
		}

	}

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

};
Last edited on
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
#include <iostream>
#include <cstring>
#include <cctype>

bool is_palindrome( const char* cstr )
{
    using namespace std ;
    int p = cstr ? strlen(cstr) - 1 : -1 ;

    for( int i = 0 ; p > i ; ++i, --p )
    {
        while( p>i && ( isspace(cstr[i]) || ispunct(cstr[i]) ) ) ++i ;
        while( p>i && ( isspace(cstr[p]) || ispunct(cstr[p]) ) ) --p ;

        if( toupper( cstr[i] ) != toupper( cstr[p] ) ) return false ;
    }
    return true ;
}

int main()
{
    const char* const cstr = "A man, a plan, a canal - Panama!" ;
    if( is_palindrome(cstr) ) std::cout << "palindrome\n" ;
    else std::cout << "not a palindrome\n" ;
}
Hey really appreciate the help! Would you be so kind as to explain what does your for loop do, cause i don't really understand it.
> explain what does your for loop do, cause i don't really understand it.

The for loop for( int i = 0 ; p > i ; ++i, --p ) is identical to the one that you wrote;
the variable names i and p in your original were deliberately retained, and have the same meaning.

The difference is in the two while loops.

while( p>i && ( isspace(cstr[i]) || ispunct(cstr[i]) ) ) ++i ;
If the next character (the one at position i) is one to be skipped , increment i till we hit a character that is not a white space or punctuation.

while( p>i && ( isspace(cstr[p]) || ispunct(cstr[p]) ) ) --p ; is identical, except that we decrement p.

The ++i, --p in the for loop get to the next pair of characters in the string; the while loops skip characters till a character to be considered for comparison is encountered.

if( toupper( cstr[i] ) != toupper( cstr[p] ) ) return false ;
If these two characters do not match, we have determined that the string is not a palindrome; there is nothing more to be done.
Topic archived. No new replies allowed.