algorithm - having a difficulty with making a palindrome program c++ -
this question has answer here:
- std::cin input spaces? 8 answers
hi code palindrome program:
void palindrome() { string input; bool checkinput, palindrome; palindrome = true; { checkinput = false; cout << "enter word, phrase or sentence :\n"; getline(cin, input); (unsigned int = 0; < input.size(); i++) { if (input[i] < 65 || input[i] > 90 && input[i] < 97 || input[i] > 122) { checkinput = true; } } } while (checkinput); (unsigned int = 0, j = input.size() - 1; < input.size(); i++, j--) { if (input[i] != input[j] && input[i] + 32 != input[j] && input[i] - 32 != input[j]) { palindrome = false; break; } } if (palindrome) { cout << "\n\nto consider letters , digits:\n"; cout << input << "\nyes, palindrome!\n"; cout << "\t\t press <enter> key menu"; fflush(stdin); cin.get(); } else { cout << "\n\nto consider letters , digits:\n"; cout << input << "\nnope, it's not palindrome\n"; cout << "\t\t press <enter> key menu"; fflush(stdin); cin.get(); } }
and when input racecar reads , says palindrome, when input race car (with space) doesn't read , says not palindrome. intend ignore spaces. appreciated! in advance!
**editted switched cin >> input getline(cin, input) , doesnt let me input words or phrases
the problem
the palindrome word spelled backwards , forwards same. therefore, can sure that, going outside in, letters need same until you're examining same letter (the total number of letters odd) or letter-searching things/examiners/markers (let's call them iterators) criss-cross.
how examine pair of letters outside inside? using index loop first last position in tandem last-to-first index loop.
how (the implementation)
let's pretend have 2 variables act iterators, , j. move forward while j move backward. start @ opposite ends:
#include <iostream> #include <string> #include <algorithm> int main() { //this our word be. std::string str; //get input std::cout << "input word, please!" << std::endl; std::getline(std::cin, str); //let's use std::erase take away our whitespaces //c++11 library <algorithm> str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); //initialize , j, our iterators //i use auto because iterator type long. it's reason why auto invented. auto = str.begin(); auto j = str.end() - 1; //you see, str.end() end, , not last letter. //that's why has -1. bool is_palindrome = true; while (i < j) //while 2 haven't crossed yet { //this std::cout shows , j @ each repeat std::cout << "i = " << *i << " ||| j = " << *j << std::endl; //if 2 characters marked 2 iterators not equal if (*i != *j) { is_palindrome = false; break; } else { //let's continue. ++i; --j; } } //if loop gets point successfully, it's palindrome. if (is_palindrome) std::cout << str << " palindrome!" << std::endl; else std::cout << str << " not palindrome." << std::endl; return 0; }
hopefully you. remember compile -std=c++11 c++11 features!
Comments
Post a Comment