c - While 或 Switch 仅检测 C 中的小写而不是大写
问题描述
我想让用户写一个字母进行选择,问题是它只检测小写字母而不检测大写字母,你能帮我吗?
#include <stdio.h>
#include <ctype.h>
int main ()
{
char choice;
printf("Will you choose A, or B?\n>");
do {
scanf(" %c", &choice);
} while (choice != 'a' && 'A' && choice != 'b' && 'B');
switch (choice) {
case 'A':
case 'a':
printf("The First Letter of the Alphabet\n");
break;
case 'B':
case 'b':
printf("The Second Letter of the Alphabet\n");
break;
}
system("pause");
return 0;
}
解决方案
在
choice != 'a' && 'A' && choice != 'b' && 'B'
'A'
并且'B'
被解释为“真”——表达式需要是
choice != 'a' && choice != 'A' && choice != 'b' && choice != 'B'
更好的选择可能是将开关移动到循环中,确保循环退出条件和开关是一致的。
推荐阅读
- jhipster - 如何检查 JHipster 环境
- html - 如果文本很长,我想加点
- python - 使用带有 json bdoy 的请求 multipartencoder 上传 Python 文件
- vba - 字符串处理参数
- c++ - 返回 char * 而不是字符串
- reactjs - 如何防止 Material-UI ThemeProvider 应用于 ReactJS 中的特定子级
- flutter - listview.builder 不在屏幕上显示项目
- c++ - 不懂 JLospinoso 书籍的模板实现
- r - R:在 visNetwork 中保留相同的默认颜色集,即使缺少组
- c++ - 为什么双向/正向运算符不支持不等式关系运算符?