该题目是为了练习switch语句的使用,先附上代码:
// primer_5_3_2.cpp : Defines the entry point for the application.
// 统计从cin读入的文本中元音字母、空格、制表符和换行符的数量。
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int vowel=0,space=0,tab=0,enter=0; //定义变量统计各类字符个数
char ch;
cout << "input the text: ('#'to over)" << endl; //提示输入文本,以'#'作为结束符
while((ch=cin.get())!='#') //逐字符进行判断,如果不是'#',则进行下面操作
{
switch(ch) //switch语句
{
case 'a': //以下十个字母都属于元音,因此无论是哪一个,元音计数变量都应加1
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowel++;
break;
case ' ': //如果是空格
space++;
break;
case '\t': //如果是制表符
tab++;
break;
case '\n': //如果是回车符
enter++;
break;
}
}
cout << "there are " << vowel << " vowels" << endl; //输出结果
cout << "there are " << space << " spaces" << endl;
cout << "there are " << tab << " tabs" << endl;
cout << "there are " << enter << " enters" << endl;
system("pause");
return 0;
}
效果如下:
需要注意的是,只要没有遇到break,则case分支会依次执行,例如判断元音的十句代码。