/******************************* * * * Lab 4 Out * * Takes a sentence form the * * command line and tests to * * see if its a palindrome * *******************************/ #include #include #include //Removes all punctuation characters from each word as entered on the command line char *cleanWords(char *word); //Accepts all words (each word has been cleaned by cleanWords), reverses the words, and tests for palindrome bool isReversible(char **all_clean_words, int no_of_words); //Combines all cleaned words into 1 sentence where each word is separated by white space char *createSentence(char **all_clean_words, int no_of_words); int main(int argc, char** argv) { char** all_clean_words; char* sentence; bool flag; int no_of_words = argc - 1; int i = 0; int j = 0; //Dynamically allocate all_clean_words all_clean_words = new char*[no_of_words + 1]; for(i = 1; i < no_of_words + 1; i++) { //Dynamically allocate all_clean_words[j] all_clean_words[j] = new char[]; //Clean each word and put into all_clean_words[j] all_clean_words[j] = cleanWords(argv[i]); j++; } //Put all of the words in to a sentence with a space between each word sentence = createSentence(all_clean_words,no_of_words); //Display the sentence cout << endl << endl << sentence << endl; //Determine if the sentnece is a palindrome flag = isReversible(all_clean_words,no_of_words); //Output the correct statement based on the return of isReversible if(flag) { cout << "Sentence is a palindrome" << endl << endl; } else { cout << "Sentence is not a palindrome" << endl << endl; } return 0; }//end of function main char* cleanWords(char* word) { char* cleaned; int i = 0; int counter = 0; cleaned = new char[strlen(word)]; for(i = 0; i < strlen(word); i++) { //if its a letter of the alphabet copy it to the cleaned array if (isalpha(word[i])) { //if its uppercase make it lowercase if(isupper(word[i])) { word[i] = word[i] + 32; } cleaned[counter] = word[i]; counter++; } } cleaned[counter] = NULL; return cleaned; }//end of function cleanWords bool isReversible(char** all_clean_words, int no_of_words) { bool flag = true; int i = 0; int j = 0; int counter = no_of_words - 1; for(i = 0; i < no_of_words; i++) { //Test for painldrome by comparing the words if(strcmp(all_clean_words[i],all_clean_words[counter]) != 0) { //if the words aren't the same flip the flag flag = false; i = no_of_words; } counter--; } return flag; }//end of function isReversible char* createSentence(char** all_clean_words, int no_of_words) { char* sentence; int i = 0; int j = 0; int counter = 0; sentence = new char[]; //Put all the cleaned words into a sentence with a space between each word for(i = 0; i < no_of_words; i++) { for(j = 0; all_clean_words[i][j] != NULL; j++) { sentence[counter] = all_clean_words[i][j]; counter++; } sentence[counter] = ' '; counter++; } sentence[counter - 1] = NULL; return sentence; }//end of function createSentence