使用switch case写一个c程序来查找一个字符是元音还是辅音

问题描述 投票:-6回答:3
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,它应该显示无效而不是辅音请快速帮助

c
3个回答
3
投票

您可以使用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");
}

0
投票
#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");
 }

在这里我使用了ASCII的概念。请参考此处的ASCII值.enter image description here


0
投票

一个选择是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");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.