利用map容器中统计文件中相同字符串的个数

来源:互联网 发布:在职软件工程硕士2018 编辑:程序博客网 时间:2024/05/19 16:51

//c++ 统计文件中相同字符串的个数

#include <iostream>

#include <string>
#include <map>
#include <fstream>

using namespace std;


int main(int argc,char*argv[])
{
map<string, int> mapA;


ifstream myfile;
//打开文件
myfile.open("1.txt", ios::in);


if (!myfile)
{
cout << "文件读错误";
system("pause");
exit(1);
}


char c[1000];
while (myfile.getline(c, 9999))
{
//cout << c << "-------------" << mapA.count(c) << endl;


if (mapA.count(c) == 0) //不存在
{
mapA.insert(pair<string, int>(c, 1));
}
else //存在
{
mapA[c]++;
}
memset(c, 0, sizeof(c));
}
myfile.close();




for (map<string, int>::iterator it = mapA.begin(); it != mapA.end(); it++)
{
cout << "key = " << it->first << "\tvalue=" << it->second <<endl;
}


cin.get();
return 0;
}
1 0
原创粉丝点击