题目:
7.编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用isalpha()来区分以字母和其他字符打头的单词,然后对于通过了isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序的运行情况如下:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consonants
2 others
答案: 书上无答案。
C++技术网辅导详解解答:
参考元音辅音说明:
元音字母(5个):a e i o u
辅音字母(21个):b c d f g h j k l m n p q r s t v w x y z
思路分析:
1.程序要求用户输入一串字符,字符串内包含好多单词(cin会自动在空格处断开输入)。界定单词的依据是空格,因为单词是用空格分隔的。最后一个单词为q而非首字母为q,即停止标志。
2.按照空格分割字符串,得到一组单词。此特性cin已支持。直接取到读取到的就是根据空白字符含空格的单词了。
3.使用isalpha()来判断首字母是否为字母。非字母,other增加1,循环重新进行continue。是字母则进一步判断。
4.判断字母属于元音还是辅音。首字母要么为元音要么为辅音。为了提高效率,我们只要判断首字母是否属于元音即可。然后统计到元音辅音数量里。
参考代码:
#include <iostream>
using namespace std;
int main()
{
char y[] = { 'a', 'e', 'i', 'o', 'u' };//除了元音之外,其他字母是辅音,所以不需要定义辅音字母数组了
string s;
int cnt_y = 0, cnt_f = 0, cnt_o = 0;
cout << "Enter words(q to quit):";
while (cin >> s && s != "q")//需要用s作为整个单词来比较"q",而不是首字母为q
{
char c = s[0];
if (!isalpha(c))//判断首字符是否为字母
{
cnt_o++;
continue;
}
bool is_in = false;//区分元音和辅音的标记
for (int i = 0;i < 5;i++)
{
if (y[i] == c)
{
cnt_y++;
is_in = true;
break;
}
}
if (!is_in)
{
cnt_f++;
}
}
cout << cnt_y << " words beginning with vowels\n";
cout << cnt_f << " words beginning with consonants\n";
cout << cnt_o << " others\n";
}