69,371
社区成员
发帖
与我相关
我的任务
分享
代码:
#include <iostream>
#include <map>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream ifile("test.txt");
if (ifile.fail())
return 1;
map<string, int> mapLetter;
while (true)
{
string line;
string letter;
getline(ifile, line);
if (ifile.eof())
break;
for (size_t i = 0; i < line.length(); ++i)
{
if (isalpha(line[i]))
letter += line[i];
if (!isalpha(line[i]) || i == line.length() - 1)
{
if (letter.length() > 0)
++mapLetter[letter];
letter.clear();
}
}
}
ifile.close();
for (map<string, int>::iterator i = mapLetter.begin();
i != mapLetter.end(); ++i)
{
cout<<i->first<<" : "<<i->second<<endl;
}
return 0;
}
测试文件 test.txt
happy,birthday. hi hi hi
happy birthday to you
happy birthday
happy birthday to you, hello
结果
birthday : 4
happy : 4
hello : 1
hi : 3
to : 2
you : 2