C++统计单词小程序
#include <fstream>
#include <string>
#include <iostream>
#include <map>
using namespace std;
int main()
{
string str;
ifstream infile;
ofstream outfile;
map<string,int> wordCount;
map<string,int>::iterator iter;
infile.open("in.txt");
outfile.open("out.txt");
//测试输入文件是否打开
if (!infile)
{
cerr<<"error:unable to open input file:"
<<infile<<endl;
return -1;
}
while(infile>>str)
{
wordCount[str]++;//统计单词出现次数
}
for (iter=wordCount.begin();iter!=wordCount.end();++iter)
{
cout<<iter->first<<":"<<wordCount[iter->first]<<endl;//标准输出
outfile<<iter->first<<":"<<wordCount[iter->first]<<endl;//输出到文件
}
infile.close();
outfile.close();
return 0;
}
浙公网安备 33010602011771号