I was trying to implement a solution for palindrome, I think my logic is correct, but my program gets stuck in an infinite loop and I get an error message of “Prep.exe has stopped working”
int main()
{
string word, reverse;
cout << "Please enter a word to test for palindrome : ";
cin >> word;
cout << "Your word is: "<< word << endl;
int i = 0;
int size = word.length() - 1;
while (size >= 0)
{
reverse[i++] = word[size--];
//cout << reverse[i++];
}
cout << "The reversed word is: " << reverse << endl;
if (word == reverse)
cout << "It is palindrome" << endl;
else
cout << "It is not a palindrome" << endl;
}
I’m not sure what I am doing wrong with my while loop. I keep on decrementing it and and I have a valid exit condition, so why does it get stuck in a loop?
You’re not getting an infinite loop; you’re getting a crash due to an Out Of Bounds access in the line
reverse[i++]becausereverseis an empty string. Try using thereverse.push_back()function instead.