利用map容器中統計文件中相同字符串的個數

//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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章