【发布时间】:2012-12-06 02:03:07
【问题描述】:
我试图实现回文的解决方案,我认为我的逻辑是正确的,但我的程序陷入了无限循环,并且我收到“Prep.exe 已停止工作”的错误消息
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;
}
我不确定我的 while 循环做错了什么。我一直在递减它,并且我有一个有效的退出条件,那么为什么它会卡在一个循环中?
【问题讨论】:
-
你有没有试过在循环之前输出
size?如果出于某种原因它为 0,则 while 将永远不会终止。 -
取消注释
//cout << reverse[i++]时的输出是什么?你可能想把它改成cout << reverse[i - 1] -
它不显示结果,直接说“它不是回文”
-
这是错误的:
reverse[i++]您不能只写入任意位置,索引需要在字符串内,并且不会为您执行边界检查。您正在写入您不“拥有”的内存,这会导致未定义的行为。
标签: c++ while-loop infinite-loop