统计文件中单词的信息

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cctype>
#include <algorithm>

using namespace std;

int main(void)
{

ifstream finput("string.txt",ifstream::in);

vector<string> vmax,vmin;
string word;
size_t wcnt = 0,ccnt = 0; //wcnt 统计字符数(不包括空格) ccnt 统计单词数(不包括数字)
string::size_type max_size = 0, min_size = 20;

while (finput >> word)//从字符串输入流种读取字
{
ccnt += word.size();
if (word.find_first_of("0123456789") == string::npos)
{//不包括数字
++wcnt;
if (ispunct(word.back()))
{//删除字中的标点
word.pop_back();
}
if (word.size() <= min_size)
{//处理长度最小单词
if (word.size() == min_size)
{
if (find(vmin.begin(),vmin.end(),word) == vmin.end())//
{//过滤重复的单词
vmin.push_back(word);
}
}
else
{
min_size = word.size();
vmin.clear();
vmin.push_back(word);
}
}
if (word.size() >= max_size)
{//处理长度最长单词
if (word.size() == max_size)
{
if (find(vmax.begin(),vmax.end(),word) == vmax.end())
{//过滤重复的单词
vmax.push_back(word);
}
}
else
{
max_size = word.size();
vmax.clear();
vmax.push_back(word);
}
}
}
}
cout << "There are " << ccnt << " characters in the sentence(except space)" << endl;
cout << "There are " << wcnt << " words in the sentence" << endl;
cout << "maximun word(s): ";
for (vector<string>::iterator iter = vmax.begin(); iter != vmax.end(); ++iter)
{
cout << *iter << " ";
}
cout << endl;
cout << "minimun word(s): ";
for (vector<string>::iterator iter = vmin.begin(); iter != vmin.end(); ++iter)
{
cout << *iter << " ";
}
cout << endl;

return 0;
}

你可能感兴趣的:(C++)