c++ - Why does my Palindrome function keep returning false? -
i have text file consists of:
1457887541 madam able ere saw elba straw? no, stupid fad. put soot on warts. class cancelled today
and when run program, strings returning false
, can't figure out why is.
#include <iostream> #include <fstream> #include <string> #include <cstring> #include <cctype> using namespace std; bool ispalindrome(string); int main() { string input; fstream namefile; namefile.open("xample.txt", ios::in); if (namefile) { cout << "now reading file: " << endl; // read item file. getline(namefile, input); // while last read operation // successful, continue. while (namefile) { cout << input << endl; //palindrome function call if(ispalindrome(input)){ cout << "it palindrome :)/> " << endl; } else { cout << "it not palindrome :'( " << endl; } // read next string. getline(namefile, input); } //close when completed cout << "done!" << endl; namefile.close(); } else { cout << "error: cannot open file.\n"; } return 0; } bool ispalindrome(string input){ int first = 0; int last = input.length() - 1; //begin loop compare first position last while(last > first){ //loop if not number or letter while(!isalnum(input[first]) && !isalnum(input[last])){ first++; last--; } if(tolower(input[first]) != tolower(input[last])){ return false; } last--; first++; } return true; }
without running/debugging code, think problem in algorithm. part of code looks it's designed around problem of spaces , punctuation.
//loop if not number or letter while(!isalnum(input[first]) && !isalnum(input[last])){ first++; last--; }
that doesn't work though. you're skipping both current first , last character if both of them not alphanum characters, should skip 1 or other of time, should separate out 2 if statements instead of 1 loop.
Comments
Post a Comment