【问题标题】:Infinite while loop C++无限循环 C++
【发布时间】: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 &lt;&lt; reverse[i++]时的输出是什么?你可能想把它改成cout &lt;&lt; reverse[i - 1]
  • 它不显示结果,直接说“它不是回文”
  • 这是错误的:reverse[i++] 您不能只写入任意位置,索引需要在字符串,并且不会为您执行边界检查。您正在写入您不“拥有”的内存,这会导致未定义的行为。

标签: c++ while-loop infinite-loop


【解决方案1】:

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

【讨论】:

  • .append() 属于哪个库?
  • 我认为push_back()append() 更合适。 append() 没有单字符重载。
  • 这是一种刺痛方法(cplusplus.com/reference/string/string/string)。实际上,甚至不要使用附加,使用string reverse(word.rbegin(), word.rend()); 并摆脱循环:P(好吧不是重点)
  • 比较 if(reverse[i]!= word[i]) check = false; 之类的 2 个字符串是否不好?
【解决方案2】:

你是否初始化了变量 reverse 只需检查并在初始化后尝试。

希望有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-26
    • 2016-08-27
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2012-02-27
    相关资源
    最近更新 更多