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

Accelerated C++ Exercise 4-5(2)

2013-11-15 16:07 323 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: