Palindromes

Hello all,

I am having a bit of trouble with a program I am writing to check if a file that first has the length, then the content contains a palindrome.

For example, if a file contains: 4 aa bb bb aa, disregarding the 4 as the length, my code should be able to recognize aa bb bb aa as a palindrome.

However if a file contains: 4aa bb bb aa, the code does recognize a palindrome... so the space between the 4 and first a is throwing the program off. Any ideas on how can I fix this?


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 <stdio.h>
#include <string>
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;

ifstream inputfile;

bool Palindrome(char *str)
{

    static int length = strlen(str);
    if (length<1)
        return 1;
    if (str[0] == str[length-1])
    {
        length -= 2;
        return Palindrome (str+1);
    }
    else return 0;

}

int main()
{
    int length1,length;
    int result;
    string content;
    char str[256];
    inputfile.open("mirror2.txt");
    inputfile>>length1;
    length = length1;
    cout<<length;
    getline (inputfile,content);
    cout<<content;
    const char* c_str();
    strcpy(str,content.c_str());
    cout<<str;
    result = Palindrome(str);
    if (result==1)
        cout<<("\nthe file contains a palindrome.\n");
    else
        cout<<("\nthe file does not contain a palindrome.\n");
    return 0;
}
Somewhat confused. If the string has a '4' in the front, then it's not a palindrome unless it also has a '4' in the back. Isn't this actually the desired behaviour?
4 is the length,

the file contains a length and then the contents that I actually want to analyze..

for instance the file reads:

4 aa bb bb aa

or

6 aa bb cc cc bb aa

The letters are the only contents i want to be analyzed by the function Palindrome.
C-style strings (char*) read in white space. So your string
4 aa bb bb aa
is being evaluated as
 aa b aa
which is not a palindrome. (Note the space before the first aa.)
However, with the other string you are not including white space, so your string is being evaluated as
aa bb aa
which is a palindrome.
How can I keep the space from being evaluated?
Using streams would probably work, but that would create some other difficulties. I would suggest just getting rid of all of the white space in your programs, or counting the white space as part of it.
I would certainly like to do that, but the problem is that I cannot change the files, they have to remain exactly the way they are.
Topic archived. No new replies allowed.