C++ 在switch里面跳出外部while循环

今天做了一次练习,发现whie循环中包含switch,switch中的break只是起到不再执行下一个case语句的作用,不会影响switch外部的while循环。如果要控制while循环的退出,可以用以下两种方式:

一、设置循环的判断条件

#include 
int main(int argc, char *argv[])
{
    bool bIsContinue = true;
    while(bIsContinue)
    {
        int num = 0;
        std::cout << "please input a number to continue:" << std::endl;
        std::cin >> num;
        switch(num)
        {
        case 1:
            std::cout << "you input is 1." << std::endl;
            break;  //此时break和continue的效果一样,都是只退出switch结构,不继续执行下面的语句
        case 2:
            std::cout << "your input is 2."<< std::endl;
            continue;
        case 3:
            std::cout << "your input is 3." << std::endl;
            bIsContinue = false;
            break;
        }
    }
    std::cout << "exiting..." << std::endl;
    return 0;
}

运行结果:

C++ 在switch里面跳出外部while循环_第1张图片

 二、设置标记(坑坑坑!!!不到万不得已(例如九重循环!)不推荐使用,因为会打乱循环结构,不利于可读性)

#include 
int main(int argc, char *argv[])
{
    while(true)
    {
Cycle1:
        std::cout<< "Cycle1"<> num;
            switch(num)
            {
            case 1:
                std::cout << "you input is 1." << std::endl;
                break;
            case 2:
                std::cout << "you input is 2." << std::endl;
                continue;
                break;
            case 3:
                std::cout << "you input is 3." << std::endl;
                goto Cycle1;
            case 4:
                std::cout << "you input is 4." << std::endl;
                goto Cycle2;
            case 5:
                std::cout << "you input is 5." << std::endl;
                goto exit0;
            }
        }
    }
exit0:
    std::cout <<"exiting..." << std::endl;
    return 0;
}

运行结果:

C++ 在switch里面跳出外部while循环_第2张图片

你可能感兴趣的:(C/C++,c++,开发语言)