学习C++小试一把

C++ PRIMER中文版 page 179

题目: 从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现它本身。跟踪重复次数最多的单词及其重复次数。输出重复次数的最大值,若没有单词重复则输出说明信息。例如,如果输入是:

how, now now now brown cow cow

则输出应表明“now” 出现了三次

 

  /*
  Name: none
  Copyright: none 
  Author: LK
  Date: 04-08-06 13:00
  Description: input a sequence of string objects,find out the word which appeared most frequently. 
*/


#include 
< iostream >
#include 
< string >
#include 
< conio.h >

using   namespace  std;

int  main()
{
    
int tmp_cnt = 1, max_cnt = 1;
    
string    word, tmp_word, max_word;
    
    cin 
>> word;
    tmp_word 
= word;
    
while(cin >> word) {
        
if(tmp_word != word) {
                tmp_cnt 
= 1;
        }

        
else {
                
++tmp_cnt;
        }

        
if(tmp_cnt > max_cnt) {
                max_cnt 
= tmp_cnt;
                max_word 
= tmp_word;
        }

        tmp_word 
= word;
    }

    
if(max_cnt == 1{
        cout 
<< "therer is no repeated word." << endl;
    }

    
else {
        cout 
<< max_word << " appears " << max_cnt << " times." << endl;
    }

    getch();
    
return 0;
}


 


缺陷:如果有同样满足要求的次数的单词出现,只会显示最先出现的那个
使用数组(OR vector<string>)存储可以解决这个问题

回来再说吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值