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

C++文件中读单词并统计输出改单词及其个数

2015-09-26 11:08 471 查看
(一)若每个单词之间只有空格或换行符,不含其它的标点符号,则可以直接读单词

#include<iostream>
#include<fstream>
#include<assert.h>
#include<string.h>
#include<map>
using namespace std;

int main()
{
ifstream in("D:\\test.txt");
assert(in!=NULL);
map<string,int>mvc;
string word;
while(in>>word)
mvc[word]++;
map<string,int>::const_iterator beg=mvc.begin();
for(;beg!=mvc.end();beg++)
cout<<beg->first<<":"<<beg->second<<endl;
return 0;
}

(二)若每个单词之间是其它的标点符号(如,或.)则可以按照以下方法读每个单词.

#include<iostream>
#include<fstream>
#include<assert.h>
#include<string>
#include<map>
using namespace std;
int main()
{
ifstream in("D:\\111.txt");
assert(in!=NULL);
map<string,int>mvc;
string word;
int i=0;
char str[200],ch;
//ch=in.get();
while((ch=in.get())!=EOF)
{
if(ch==','||ch=='.'||ch==' ')
{
str[i]='\0';
word=str;
mvc[word]++;
i=0;

}
else if(ch=='\n')//不加该判断就会出现“”字符串。
{
continue;
}
else
{
str[i++]=ch;
}
}
map<string,int>::const_iterator beg=mvc.begin();
for(; beg!=mvc.end(); beg++)
cout<<beg->first<<":"<<beg->second<<endl;
system("pause");
return 0;
}
当然你也可以根据方法(一)中方法,读取每个单词时除掉后面的标点符号!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: