c++ - While 和 Do/While 循环意外中断

标签 c++ while-loop do-while

该程序旨在无限循环....所以如果有人输入 5,它会要求输入另一个数字(5 或 9),如果他/她输入 9,它会要求输入 5 或 9...无限循环.

using namespace std;

int main()
{
    cout << "Hello world! Enter a number" << endl;
    int x;
    cin >> x;

    while (x == 5)
    {
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Try again, you got 5" << endl;
        cin >> x;

    }

    while (x == 9)
    {
        cout << "You got 9, try again mate" << endl;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        cin >> x;
    }
return 0;
}

但我不明白当我切换数字时(比如“5”到“9”再回到“5”)程序就停止了。

我认为是因为在 Loop #1 和 Loop #2 执行完后,程序再也没有返回到其中任何一个,而是继续直接“返回 0”,但我不知道如何让程序返回到两个循环。

PS:我试过切换到 do-while 循环并从括号中取出“cin”语句,但它们没有解决问题。

最佳答案

您的代码没有提供所需的行为,因为当第二个 while 循环结束时,您没有重复该过程并且程序结束。

所以您想要的是循环直到用户输入59 以外的一些数字。
为了做到这一点,我们使用 while 循环运行到无穷大,我们使用如果用户输入的数字不同于 59,则 break 可退出无限循环。

您可以像这样修改代码:

using namespace std;

int main()
{
    cout << "Hello world! Enter a number" << endl;
    int x;

    while(1){
        cin >> x;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        if(x == 5)
            cout << "Try again, you got 5" << endl;
        else if(x == 9)
            cout << "You got 9, try again mate" << endl;
        else
            break;        
    }

    return 0;
}

关于c++ - While 和 Do/While 循环意外中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226712/

相关文章:

c++ - 从 Visual Studio 2008 解决方案创建 Unix makefile

c++ - 另一个别名的模板别名

java - ActionEvent 后的无限 while 或 for 循环在 swing 中不起作用。为什么?

java - Java 中的 while 循环

java - 初学者循环问题 - while ... do

具有多种功能的 C++ SSE 优化

C++ 将 int 分隔为 char 数组

php - PHP while循环中MYSQL更新和删除查询

Java - while 循环中的 ObjectInputStream boolean 赋值

c++ - "} while (0);"总是等于 "break;} while (1);"吗?