您的位置:首页 > 编程语言 > C语言/C++

C++ Primer Plus第六版编程练习6.7解答

2015-03-09 22:42 471 查看
说明:本文用了两种方法完成这道题,一种是用string类接收输入,另一种是用cin.get(ch)接收输入(因为自己一开始没看清楚题目o(╯□╰)o)

 一、用string类接收输入的方法

这个很简单,就直接贴代码了。

#include <iostream>
#include <cctype>  //for isalpha()
#include <string>

using namespace std;

int main()
{
cout<<"Enter the words(q to quit):\n";
int vowel=0,consonant=0,other=0;
string word;
while(cin>>word)
{
if(word=="q")  //如果输入为q则结束
break;
if(isalpha(word[0]))  //先判断是字母开头
{
if(word[0]=='a'||word[0]=='e'||word[0]=='i'||word[0]=='o'||word[0]=='u')//元音字母开头
vowel++;
else  //辅音字母开头
consonant++;
}
else    //非字母开头
other++;
}
cout<<vowel<<" words beginning with vowels.\n";
cout<<consonant<<" words beginning with consonants.\n";
cout<<other<<" others.\n";
return 0;
}


二、用cin.get(ch)接收输入

6.9题目本身不是很难,但是我一开始没仔细看题目说的“每次读取一个单词”,于是一开始写了个吃力不讨好的程序——每次只读取一个字符,直到遇到q结束。

后来一写发现一次只读取一个字符要考虑的问题反而比较复杂(真是自己为难自己OTL)

其中最重要的一点:每次读取一个单词的话要考虑如何读取到一个完整的单词(或数字输入)!

代码如下:

#include <iostream>
#include <cctype>  //for isalpha()

using namespace std;

int main()
{
cout<<"Enter the words(q to quit):\n";
int vowel=0,consonant=0,other=0;
char ch;
while(cin.get(ch))  //开始读取一个新的输入
{
if(ch=='q')  //遇到q则须判断是否是停止的标志
{
cin.get(ch);
if(ch=='\n')   //若q后面接着的输入是回车键证明是结束标志
break;
else    //否则证明q只是一个单词的开头字母
{
consonant++;
do
{
cin.get(ch);
}
while(ch!=' ' && ch!='\n');  //读取这个单词剩下的字母
continue;    //跳转到最外部的while循环,重新读取下一个单词
}
}
if(isalpha(ch))
{
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
vowel++;
else
consonant++;
}
else    //非字母开头的输入
other++;
do
{
cin.get(ch);
}
while(ch!=' ' && ch!='\n');   //无论是什么开头的输入,完整读取它,直到遇到空格或换行符
}
cout<<vowel<<" words beginning with vowels.\n";
cout<<consonant<<" words beginning with consonants.\n";
cout<<other<<" others.\n";
return 0;
}


比较:其实两种实现方法最主要的区别在于用string可以直接一次接收一个单词(或数字)的输入二不用自己去判断,而用cin.get(ch)的话就要通过检查是否已经到达空格或者换行符来确定是否已经是一个完整的单词了。

PS:有兴趣的亲可以试试第二种“瞎折腾”的方法,呵呵……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息