元音字母的个数

例1:计算一组字符中各个元音字母的个数

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int main()
{
    
    
    //分别为每个元音字母设置计数器
    int acnt = 0,ecnt = 0,icnt = 0,ocnt = 0,ucnt = 0;
    char ch;
    
    //一直读入字符,直到遇到回车为止
    while ((ch = getchar()) != '\n')
    {
    
    
        switch(ch)
        {
    
    
            case 'a':
                acnt++;
                break;//使用continue效果一样
            case 'e':
                ecnt++;
                break;
            case 'i':
                icnt++;
                break;
            case 'o':
                ocnt++;
                break;
            case 'u':
                ucnt++;
                break;
        }
    }
    
    //输出结果
    cout << acnt << endl;
    cout << ecnt << endl;
    cout << icnt << endl;
    cout << ocnt << endl;
    cout << ucnt << endl;
    return 0;
}

在这里插入图片描述

例2:计算一组字符中所有元音字母的总数

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int main()
{
    
    
    //设置计数器
    int all_cnt = 0;
    char ch;
    
    //一直读入字符,直到遇到回车为止
    while ((ch = getchar()) != '\n')
    {
    
    
        switch(ch)
        {
    
    
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                all_cnt++;
                break;
        }
    }
    
    //输出结果
    cout << all_cnt << endl;
  
    return 0;
}

在这里插入图片描述

例3:分别计算一组字符中元音字母和非元音字母的个数

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int main()
{
    
    
    //vowel 元音
    //设置计数器
    int vowel_cnt = 0;
    int other_cnt = 0;
    char ch;
    
    //一直读入字符,直到遇到回车为止
    while ( (ch = getchar()) != '\n')
    {
    
    
        switch(ch)
        {
    
    
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                vowel_cnt++;
                break;
            //如果字符不是a/e/i/o/u,那么语句直接从default开始执行
            default:
                other_cnt++;
                break;
        }
    }
    
    //输出结果
    cout << vowel_cnt << endl;
    cout << other_cnt << endl;
  
    return 0;
}

最后补充一个小细节
cin和getchar的输入流中会保留回车,而getline(cin,s)的输入流中不会保留回车,所以要会使用getchar吃掉回车

猜你喜欢

转载自blog.csdn.net/smallrain6/article/details/113099185
今日推荐