如何验证小写和大写字母 [英] how to validate both lowercase and uppercase letters
本文介绍了如何验证小写和大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面我写了一个评估字母等级的程序,并根据分数的不同打印一条消息。假设我想从用户输入中获取该信息,我如何能够接受大写和小写字母?
Below I have written a program to evaluate a letter grade and print a message based on how well the score is. Let's say I wanted to get that information from the user input, how would I be able to accept both lower and upper case letters?
#include <stdio.h>
int main (){
/* local variable definition */
char grade = 'B';
if (grade == 'A'){
printf("Excellent!\n");
}
else if (grade == 'B' || grade == 'C'){
printf("Well done\n");
}
else if (grade == 'D'){
printf("You passed\n" );
}
else if (grade == 'F'){
printf("Better try again\n" );
}
else {
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
推荐答案
我如何能够接受大写和小写字母?
how would i be able to accept both lower and upper case letters?
你想要标准化年级
使用 toupper()
在执行支票之前。
You want to normalize grade
using toupper()
before performing the checks.
您还可以使用 switch()
语句如
switch(toupper(grade)) {
case 'A':
// ...
break;
case 'B':
case 'C': // Match both 'B' and 'C'
// ...
break;
}
更难的方法是检查小写:
The harder way is to check for lower case as well:
if (grade == 'A' || grade == 'a'){
// ...
}
else if (grade == 'B' || grade == 'b' || grade == 'C' || grade == 'c'){
// ...
}
// ...
这篇关于如何验证小写和大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文