I was making a program that could count the total number of palindromes in a sentence.
My instructor has advised us to use the 'string' class to make this program.
the idea of making such a program is that first I get a word from the sentence and then check whether it is a palindrome or not...
Here is the code:
#include <iostream>#include <string>using namespace std;bool IsPalindrome(const string &word){ int size=word.length(), n=size/2; bool equal=true; for (int i=0, j=size-1; i<n && equal; i++, j--) if (word!=word[j]) equal=false; return equal;}bool IsAlphabet(const string &str, int index){ return ((str[index]>=65 && str[index]<=91) || (str[index]>=97 && str[index]<=123));}int get_palindromes(const string &sentence){ int num=0, j, size=sentence.length(); string word("nothing"); for (int i=0; i<size; i++) if (IsAlphabet(sentence, i)) { j=i; while (IsAlphabet(sentence, j+1)) j++; word.erase(); word.insert(0, sentence, i, j+1); // cout << word << endl; if (IsPalindrome(word)) num++; i=j; } return num;}int main(){ int n; string str; cout << "Enter a sentence: "; getline(cin, str); n=get_palindromes(str); cout << "There are " << n << " number of palindromes. "; cin.get(); return 0;}
Input that I give is 'rotor and noon' or you can give any other input.. It does'nt work and I cant figure it out.. can someone please instruct what is going wrong here..?