【问题标题】:How do you have a do-while loop run again with the choice of the user wanting to run it again? [closed]如果用户选择想要再次运行它,你如何让 do-while 循环再次运行? [关闭]
【发布时间】:2021-12-02 07:52:31
【问题描述】:

当使用 do-while、while 或 for 循环时,在我尝试询问用户是否想再次运行某个函数后,我似乎总是不断出现无限循环。

  #include <iostream>

int main()
{
    char choice = 'y';
    
    while (choice == 'y')
    {
        // Do something
        
        // Exits while loop
        
    }
    
    std::cout << "Would you like to do it again?" << std::endl;
    
    std::cin >> choice;
}

有没有我忘记的代码行?

【问题讨论】:

  • 你必须提供一个更好的minimal reproducible example 来演示一个无限循环的运行,这样我们才能准确地看到你是如何读取输入并尝试对其采取行动的。无论如何,在您显示的代码中,用户choice 的提示是在循环完成后执行的,所以它是无用的。将它移到 inside 循环中。
  • 请尝试向您的rubber duck 解释代码。尤其要说明您在循环内何时何地修改choice,以便循环可能结束。
  • 告诉你的橡皮鸭 while循环如何退出,和之后会发生什么std::cin &gt;&gt; choice;
  • “在我尝试询问用户是否想再次运行一个函数之后”——这对您的代码 sn-p 是否准确?无限循环发生之后提示Would you like to do it again? 显示?准确描述症状对调试很有用。小细节很重要。

标签: c++ loops while-loop char do-while


【解决方案1】:

对于这种情况下的初学者,最好用 while 循环代替 do-while 循环。例如

#include <iostream>

int main()
{
    char choice = 'y';
    
    do
    {
        // Do something
        
        std::cout << "Would you like to do it again?" << std::endl;
    
        std::cin >> choice;
    } while ( choice == 'y' || choice == 'Y' );
    
}

【讨论】:

    【解决方案2】:

    因为问题(和输入读取)应该在 while 循环内:

    #include <iostream>
    
    int main()
    {
        char choice = 'y';
        
        while (choice == 'y') {
            // Do something
    
            std::cout << "Would you like to do it again?" << std::endl;
            std::cin >> choice;
        }
    }
    

    更新:按照 Remy 的建议添加 do-while 循环。

    int main()
    {
        char choice;
        do {
            // Do something
    
            std::cout << "Would you like to do it again?" << std::endl;
            std::cin >> choice;
        } while (choice == 'y');
    }
    

    【讨论】:

    • 或者,使用do..while 循环:char choice; do { ... std::cin &gt;&gt; choice; } while (choice == 'y');
    猜你喜欢
    • 2016-07-20
    • 2019-06-06
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多