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

C语言Case语句异常:选择选项后重复显示菜单

C语言Switch-Case菜单看似无法进入分支的问题排查

问题描述

我在调试一段C语言菜单代码时遇到了困惑:无论选择1、2还是其他有效选项,程序都会重复显示菜单,看起来像是无法进入对应的Case分支执行逻辑。我原本期望选择对应选项后能进入Case 1或Case 2执行相应的输出。

相关代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char ** argv) {
 int flag = 1;
 while (flag) {
 //Print menu
 printf("1: Say hello\n");
 printf("2: Say goodbye\n");
 printf("0: exit\n");
 printf("Enter choice :");
 //read input
 char buffer[10];
 fgets(buffer, 10, stdin);
 //convert to number
 int number = atoi (buffer);
 //work on input
 switch (number) {
 case 1:
 printf("hello world\n");
 break;
 case 2:
 printf("goodbye world\n");
 break;
 case 0:
 printf("Exiting...\n");
 flag = 0;
 break;
 default:
 printf("INVAID INPUT\n");
 break;
 }
 }
 return 0;
}

问题解决

经过确认,这段代码本身运行完全正常,问题出在自己的疏忽:执行对应分支后输出的提示信息(比如hello world)已经打印,但自己没注意到,误以为程序没进入分支,导致觉得菜单一直在重复显示。

比如输入1后,程序会先打印hello world,然后因为flag的值还是1,会再次循环显示菜单——这是代码的正常逻辑,并不是分支没执行,只是没留意到中间的输出内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:14:09