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

说明:本文用了两种方法完成这道题,一种是用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:有兴趣的亲可以试试第二种“瞎折腾”的方法,呵呵……



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值