Reputation: 3311
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?
Upvotes: 0
Views: 1376
Reputation: 9278
You're not getting an infinite loop; you're getting a crash due to an Out Of Bounds access in the line reverse[i++]
because reverse
is an empty string. Try using the reverse.push_back()
function instead.
Upvotes: 6
Reputation: 31
did you initialize the variable reverse just check that and try after initializing it.
hope that works
Upvotes: 0