C++统计单词小程序

来源:互联网 发布:淘宝卖家怎么打折 编辑:程序博客网 时间:2024/05/16 19:55
#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;}