Palindrome detector. Palindrome is any word/sentence/phrase that reads the same foreword and back.
I'm in the middle of creating a program that accepts a sentence, phrase, or word. Then checks to see if it's a palindrome, I'm just having trouble on what to pass to my function. The function must be a recursion function. Here is what I got so far...

#include <iostream>
#include <string>
using namespace std;

//function prototype
bool Detector(char[],char[], int);

bool Detector(char*,char*, int num)
{
	
	
	
}

int main() 
{
	const int SIZE = 81;
	char string[SIZE];
	char revString[SIZE];

	
	int strLength = 0;   //to hold length of string
	int count = 0;
	

	cout << "What is the sentence?    " ;
	cin.getline (string, SIZE) ;
	
	strLength = strlen(string);  
	strLength--;                //gather length of string and subtracting the element with \o

	while(strLength != -1)       //creating a reversed copy of the string
	{
		revString[count] = string[strLength];
		count++;
		strLength--;	

	}
	 revString[count] = '\0';  //putting \0 at the end of the string
	
	cout << revString;  //testing to see if it was copied correctly


}

Is that right? Putting two char* in my function. Because I want to send both the regular string and the reversed copy of it to the function. Any tips on this would be great. I'm not too good with pointers and such ( I need to familiarize myself with them more). Thanks in advance!

Recommended Answers

All 2 Replies

Some comments:

strlen already returns the correct length, you don't need to decrease the length to account for the null-char.

I don't think the revString is necessary.

You can define a pointer to the start of string, and one to the end.. compare them and increase the first pointer, decrease the second pointer.

e.g.

char szInput[SIZE];
 ...
char* p1 = szInput;
char* p2 = &szInput[strLength-1]; // -1 not because of '\0', but because string's index starts at 0

while( <something, for you to think about ;) ) {
    if( *p1 != *p2 )
        ; // it's not a palindrome
    p1++;
    p2--;
}

so all you need to hand over to your function is a char* and the size(which is not strictly necessary... but nicer)

That makes a lot more sense then using a reverse string. I will try this tonight. I'm guessing the condition statement for the while loop will have some sort of counter until I get to the last element of the array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.