Accelerated C++ Exercise 4-5(2)

#ifndef GUARD_read_words_h
#define GUARD_read_words_h

#include <vector>
#include <istream>
#include <string>
std::istream& read_words(std::istream& is, std::vector<std::string>& words);

#endif GUARD_read_words_h
#include "read_words.h"
using std::istream;
using std::string;
using std::vector;
istream& read_words(istream& in, vector<string>& words)
{
	if(in)
	{
		words.clear();
		string word;
		while(in >> word){
			words.push_back(word);
		}
		in.clear();
	}
	return in;
}
#include "read_words.h"
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::sort;

int main()
{
   vector<string> words;

   cout << "Enter a few words, followed by end-of-file: " << endl;;

   if (read_words(cin, words))
   {
	   typedef vector<string>::size_type vec_sz;
	   vec_sz size=words.size();
	   if(size==0)
	   {
		   cout << endl << "You didn't enter any words. "
            "Please try again." << endl; 
		   system("pause");
		   return 1;
	   }
	   sort(words.begin(),words.end());

	    string current_word;
		int count;

		current_word =words[0];
		count=1;

		for(vec_sz current_index=1; current_index < size; ++current_index)
		{
			if (current_word != words[current_index])
			{
				cout << "The word \"" << current_word << "\" appears "
					<< count << " times." << endl;

				current_word = words[current_index];
				count = 0;
			}
			
			++count;
		}
		cout << "The word \"" << current_word << "\" appears "
			<< count << " times." << endl;
   }
   else
   {
	   cout << "An error occurred during input." << endl;
	    system("pause");
	   return 1;
   }
   system("pause");
   return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值