c语言中如何让switch一直选泽
时间: 2023-11-13 12:02:23 浏览: 35
在 C 语言中,switch 语句通常用于根据不同的条件执行不同的代码块。如果你想让 switch 一直选中某个 case,可以使用一个无限循环结构(如 while 或 for 循环),并在其中放置 switch 语句。
例如,以下代码会一直循环执行 switch 语句,直到用户输入了一个退出命令:
```c
#include <stdio.h>
#include <string.h>
int main() {
char input[10];
while (1) { // 无限循环
printf("请输入一个命令:");
scanf("%s", input);
switch (input[0]) {
case 'h':
printf("帮助文档\n");
break;
case 'v':
printf("版本信息\n");
break;
case 'q':
printf("退出程序\n");
return 0;
default:
printf("无效命令,请重新输入\n");
break;
}
}
return 0;
}
```
在上面的代码中,我们使用了一个 while 循环来保证 switch 语句会一直被执行。如果用户输入了 q 命令,则程序会退出循环并结束执行。