This program takes a string as an input, and checks if is a palindrome.
This is supposed to be case and space insensitive.
Once I run it, the command prompt pops up, but as soon as I press enter
after entering a space, or entering 'n' after the message (try again(Y/N)?),
the program crushes, a new window called 'xutility' appears and
it indicates line 221 :
*_Pnext != nullptr; *_Pnext = (*_Pnext)->_Mynextiter)
Thank you.
The issue is solved, but now there is another one.
The program, after showing the "try again" message,
it stops and does not let me choose yes or no.
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main()
{
char answer;
do
{
// get a whole line of text, including spaces and punctuation
std::cout << "Enter a string:\n";
std::string input;
std::getline(std::cin, input);
std::cout << '\n';
// create a 'temp' string to modify for palindrome testing
std::string pali = input;
// erase whitespace
pali.erase(std::remove_if(pali.begin(), pali.end(), ::isspace), pali.end());
// erase punctuation
pali.erase(std::remove_if(pali.begin(), pali.end(), ::ispunct), pali.end());
// convert the string to lower case
// could use upper case if desired
std::transform(pali.begin(), pali.end(), pali.begin(), ::tolower);
// compare to a temp reversed string
if (pali == std::string(pali.rbegin(), pali.rend()))
{
std::cout << '\"' << input << "\" is a palindrome.\n";
}
else
{
std::cout << '\"' << input << "\" is NOT a palindrome.\n";
}
std::cout << "\nDo you want to try again? ";
std::getline(std::cin, input);
answer = input[0];
} while ('y' == ::tolower(answer));
}
Enter a string:
Madam I'm Adam
"Madam I'm Adam" is a palindrome.
Do you want to try again? y
Enter a string:
Hello George
"Hello George" is NOT a palindrome.
Do you want to try again? n
Interesting way to look at the problem, JLBorges. I'm gonna have to take a few bites and ruminate on how you do things for stripping out the extraneous characters.
thank you everybody for your feedback.
However, would it be possible to slightly edit my code in order to make it work?
Let me know if I am a way off the track.
And by the way, I am using visual studio 2017.
If you're going to type in lines containing spaces, you can't use cin >>, because cin >> will stop at the first space. Then, the NEXT cin >> will read the NEXT word.
That's why it ends if you enter a line with a space. Because cin >> answer; reads that next word, and that next word isn't 'Y' so the program ends.
getline() in this form requires a string; variable answer is only a char.
Either make answer a string (in which case you would need double quotes for both possibilities on line 39) or clear the remainder of the input up to and including the line feed by changing line 38 to: cin >> answer; cin.ignore( 1000, '\n' );
Your earlier getline() on line 33 is entirely correct.