练习:使用 switch 判断 Y/N 确认输入
1. 程序功能与场景
这是一个经典的命令行交互确认模型,模拟文件保存、操作执行等场景中的”Y/N 确认对话框”。程序读取用户单个字符输入,判断其意图并给出对应反馈。
2. 完整代码
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char answer = 0; /* 存储用户输入的字符 */
printf("输入 Y 或者 N: ");
scanf("%c", &answer);
switch (answer)
{
case 'y':
case 'Y':
printf("\n你的回答是肯定的。");
break;
case 'n':
case 'N':
printf("\n你的回答是否定的。");
break;
default:
printf("\n你没有正确回答。。。");
break;
}
return 0;
}Code language: PHP (php)
3. 运行结果
| 输入 | 匹配分支 | 输出 |
|---|---|---|
y | case 'y' → 穿透 → case 'Y' | “你的回答是肯定的。” |
Y | case 'Y' | “你的回答是肯定的。” |
n | case 'n' → 穿透 → case 'N' | “你的回答是否定的。” |
N | case 'N' | “你的回答是否定的。” |
x / 其他 | default | “你没有正确回答。。。” |
4. 核心要点解析
| 要点 | 说明 |
|---|---|
多 case 串联(穿透正用) | case 'y': case 'Y': 共用同一段 printf,避免重复代码;n/N 同理 |
scanf("%c", &answer) | 读取单个字符,%c 前不需要空格(与之前读数字不同,此处无缓冲区残留问题) |
default 兜底 | 捕获所有非 Y/N 输入,防止程序”静默”无响应 |
5. 使用 toupper() / tolower() 简化 case
优化思路:将输入统一转为大写(或小写),switch 中只需写一个 case,大幅精简代码。
版本一:toupper() 统一转大写
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char answer = 0;
printf("输入 Y 或者 N: ");
scanf("%c", &answer);
switch (toupper(answer))
{
case 'Y':
printf("\n你的回答是肯定的。");
break;
case 'N':
printf("\n你的回答是否定的。");
break;
default:
printf("\n你没有正确回答。。。");
break;
}
return 0;
}Code language: PHP (php)
版本二:tolower() 统一转小写
switch (tolower(answer))
{
case 'y':
printf("\n你的回答是肯定的。");
break;
case 'n':
printf("\n你的回答是否定的。");
break;
default:
printf("\n你没有正确回答。。。");
break;
}Code language: JavaScript (javascript)
Previous: 练习:使用 switch 语句实现幸运数字抽奖
Next: goto 语句