如何用开关中断while循环

How do I break from a while loop with a switch?

本文关键字:while 循环 中断 开关 何用      更新时间:2023-10-16

>我试图从开关语句中的 while 循环中断,但它不起作用。我得到一个无限循环。为什么?

int main()
{
    int n;
    while (std::cin >> n)
    {
         switch (n)
         {
         case 4:
             break;
             break;
         default:
             std::cout << "Incorrect";
             break;
         }
    }
}

你会得到一个无限循环,因为这不是break的工作方式。执行第一个break后,退出 switch 语句,第二个break永远不会执行。您必须找到另一种退出外部控制结构的方法。例如,在 switch 语句中设置一个标志,然后在末尾或在循环条件中检查该标志。

while (std::cin >> n)
{
    bool should_continue = true;
    switch (n)
    {
    case 4:
        should_continue = false;
        break;
    default:
        std::cout << "Incorrect";
        break;
    }
    if (!should_continue)
        break;
}

switch内的break会断开开关。执行以下操作:

while (std::cin >> n)
{
     if(n == 4)
         break;
     switch (n)
     {
     //...Other case labels
    default:
         std::cout << "Incorrect";
         break;
     }
}