You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++ switch的default分支提示重输入并循环执行switch

实现重复执行switch的方案

你猜的没错,确实需要用while循环把整个switch包裹起来,同时得加个退出机制,让用户能主动结束程序。下面是具体的实现方式:

核心思路

  • 用while循环包裹switch,循环持续到用户输入退出指令(比如输入q)
  • 把用户输入提示统一放在循环开头,避免代码重复
  • 调整default分支的逻辑,只提示错误,让循环自动进入下一轮重新请求输入

修改后的完整代码

// 初始化choice,确保能进入循环
char choice = ' ';

// 循环条件:当用户输入不是'q'时持续运行
while (choice != 'q') {
    std::cout << "Choice of search method ([l]inear, [b]inary, [r]recursiveBinary, [q]uit)?" << std::endl;
    std::cin >> choice;

    switch(choice){
        case 'l' :
            ct.Start();
            count = LinearSearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'b' :
            ct.Start(); 
            Sort(new_books, requested_books); 
            count = BinarySearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'r' :
            ct.Start();
            Sort(new_books, requested_books); 
            count = RecursiveBinarySearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'q':
            std::cout << "Exiting program..." << std::endl;
            break;
        default : 
            std::cout << "Incorrect choice, please try again.\n";
            // 这里不需要重新cin,循环会自动回到开头重新提示
    }
}

关键细节说明

  • 循环开始前初始化choice,保证第一次能顺利进入循环
  • 在循环开头统一输出输入提示,加上退出选项q,让用户清楚所有可操作项
  • 新增case 'q'分支专门处理退出逻辑,用户输入q时循环终止
  • default分支只提示错误,不用手动读取输入,循环会自动回到顶部重新请求输入,避免代码冗余

内容的提问来源于stack exchange,提问作者Jason Ma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:40:22