include
include
void main() {
char ch;
clrscr();
printf("Enter a character:");
scanf("%c",&ch);
switch(ch) {
case 'a': case 'A': case 'e': case 'E': case 'i': case'I': case'o': case'O': case'u': case'U':
printf("Vowel");
break;
default:
printf("Consonant");
getch();
}
还给出一个功能,如果我们输入数字或某些特殊字符,如@,#etc,它应该显示无效而不是辅音请快速帮助
您可以使用isalpha()
查看字符是否是字母。你可以通过使用case
将字符转换为小写来减少你使用的tolower()
语句的数量,这使得代码更简单,你不太可能错过任何东西。
if(isalpha(ch)) {
switch(tolower(ch)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel");
break;
default:
printf("Consonant");
break;
}
} else {
printf("Invalid");
}
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("Enter a character:");
scanf("%c",&ch);
if((ch >= 65 && ch <= 90)||(ch >= 97 && ch <= 122))
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case'I':
case'o':
case'O':
case'u':
case'U':
printf("Vowel");
break;
default:
printf("Consonant");
}
else
printf("Invalid");
}
一个选择是strchr
。它会查找字符串中特定字符的出现,并且可以很好地进行优化。
bool isvowel (char ch)
{
return strchr("aeiou", tolower(ch)) != NULL;
}
就是这样。完整示例:
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
bool isvowel (char ch)
{
return strchr("aeiou", tolower(ch)) != NULL;
}
int main (void)
{
for(unsigned char i='A'; i<='Z'; i++)
{
char ch = (char)i;
printf("%c: %s\n", ch, isvowel(ch) ? "vowel" : "consonant");
}
}