For the getString() function - Prompts the user to enter a string
Note: Use cin.get() in a while loop to read one character at a time.
The loop should stop when the enter key ('\n') is encountered.
parameters:
-pass the stack object by reference
-Pass the letters array
isPalindrome() - Compares the items on the stack to the items in the letters array.
parameters:
-pass the stack object by reference
-Pass the letters array |
It doesn’t seem isPalindrome is required to be a method of class stack, does it?
Is it required in the part of the assignment you didn’t post?
Let’s see if we agree about what the assignment requires:
a) A stack works this way: when you put an element into the stack, that element prevents the previous one to be accessed - it’s a LIFO (last in - first out) container.
It means you can only access the last element inserted (or the
top element, whatever you want to call it).
The only way to access elements in a stack is to remove them one by one, starting from the last.
So, if you put a sequence of characters (usually called a string) inside a stack, when you pull them out, what you get is the original sequence (string) in reverse order.
b) When people speak about palindromes, it is implicit that spaces are not taken into account and also the string must be ‘case insensitive’.
c) If you put a string into a stack and later
--> you compare your original string, character by character from left to right, to what you pop out from the stack, you are actually
--> comparing your string characters left to right to your string characters right to left
So, what your assignment requires is:
- Purpose: ask the user a string and discover if it is palindrome.
Steps:
- Inside a getString() function, ask the user a string
- Read it character by character (by means of std::cin.get)
- Since you are reading it character by character, you can save it both in a ‘normal’ string container (a std::string, a C-Style array…) and in a stack.
- It implies that getString() function should ‘be aware’ both of a string container and of a stack.
- Remember you don’t need to save all characters!!
(Note: you can begin by writing a simpler version of your function which takes all characters and then test it by passing strings that have neither spaces nor uppercase letters - later you can develop the complete version)
- In a isPalindrome() function,
define a loop that reads one character from the string and pops one character from the stack and compares them.
If all the characters match, state the string is palindrome.
Happy coding!