Checking for a palindrome in a file.

I'm trying to read a file, and test to see if it is "mirrored". My program always displays the file as mirrored. I think most of my problem is in the initial function.


#include <iostream>
#include <cstring>
#include <fstream>


using namespace std;

bool isMirrored(string line)
{

int strlen = line.size();

if ( line[0] != line[strlen - 1] )
return false;

else
return isMirrored(line.substr(1, strlen -2));

}

int main()
{
string line;
ifstream infile;
infile.open ("lab7b.txt");
getline(infile,line);

isMirrored(line);

if (isMirrored)
{
cout << "This file is mirrored.";
}

else
{
cout << "This file is not mirrored.";
}


return 0;

}
Last edited on
Your problem is here:

if (isMirrored)

isMirrored is a function pointer, since isMirrored is the name of a function that actually exists that pointer is not 0, so it's true, so you'll always get the "is mirrored" output.

But really, it would be much more straightforward if you'd implement isMirrored with a loop instead of with recursion (and it would make it much less prone to overflowing the stack).

In your recursive function, you don't have a condition where isMirrored will return true. You will either return false or call another instance of isMirrored which will inevitably return false eventually. Therefore isMirrored(string) will always be false, it's just a matter of time.
Actually, it will throw an out_of_range exception after a while.
I know using loops would be easier, but unfortunately I HAVE to write this recursively. Thank you very much. I got it working finally.
Topic archived. No new replies allowed.