gpt4 book ai didi

c++ - 无限 while 循环 C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:52 26 4
gpt4 key购买 nike

我正在尝试实现回文的解决方案,我认为我的逻辑是正确的,但是我的程序陷入了无限循环并且我收到“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 循环做错了什么。我继续递减它并且我有一个有效的退出条件,那么为什么它会陷入循环?

最佳答案

您不会遇到无限循环;由于 reverse[i++] 行中的越界访问导致崩溃,因为 reverse 是一个空字符串。尝试改用 reverse.push_back() 函数。

关于c++ - 无限 while 循环 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13735811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com