如何在不终止整个程序的情况下退出switch语句

问题描述 投票:0回答:1

我尝试在线搜索此问题的解决方案,但未找到任何内容。

如何在不必终止程序的情况下退出switch语句?

 #include <iostream>

 int main() {

    unsigned int ch;
    while(1){
        std::cout << "Insert choice: " << std::endl;
        std::cin >> ch;

        switch(ch){
            case 1: std::cout << "case 1" << std::endl;
                break;
            case 2: std::cout << "case 2" << std::endl;
                break;
            default: exit(1); //here
        }
    }

    //unreachable code
    std::cout << "After switch. I want to go here!" << std::endl; //here

    return 0;
}

谢谢!

c++ switch-statement exit
1个回答
0
投票

尝试一下

#include <iostream>

 int main() {

    unsigned int ch;

    // Put a flag into the while loop, that you can later 'switch off'
    bool run = true;
    while(run){

        switch(ch){
            case 1: std::cout << "case 1" << std::endl;
                break;
            case 2: std::cout << "case 2" << std::endl;
                break;
            default: 
                run = false; // Set 'run' to 'false' to exit the while loop.
                break;
        }
    }

    std::cout << "After switch. I want to go here!" << std::endl; //here

    return 0;
}

使用您提供的代码,似乎不需要while循环。

#include <iostream>

 int main() {
    unsigned int ch;
    switch(ch){
      case 1: 
        std::cout << "case 1" << std::endl;
        break;
      case 2: 
        std::cout << "case 2" << std::endl;
        break;
      default: 
        break;
    }
    std::cout << "After switch. I want to go here!" << std::endl; //here
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.