#include <map>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class countWord
{
public:
map<string, int> count;
map<string, vector<int>> rows;
string sourceString;
int row;
countWord(const string &fileName)
{
fstream fin;
row = 1;
fin.open(fileName, ios::in);
while (getline(fin, sourceString) && sourceString != "@")
{
for (int i = 0, j = 0; i < sourceString.size(), j < sourceString.size();)
{
if (sourceString[i] != ' ' && sourceString[i] != ',' && sourceString[i] != '.')
{
i++;
}
else
{
count[sourceString.substr(j, i - j)]++;
rows[sourceString.substr(j, i - j)].push_back(row);
j = i + 1;
i++;
}
}
row++;
}
fstream fout;
fout.open("wordCount.txt", ios::out);
sourceString.clear();
auto itrC = count.begin();
for (; itrC != count.end(); itrC++)
{
if (itrC->first == "" || itrC->first == "@")
continue;
fout << itrC->first << endl;
fout << "次数" << itrC->second << " ";
fout << "出现的行号有:";
for (auto c : rows[itrC->first])
{
fout << c << " ";
}
fout << endl;
}
}
};
int main(int argc, char const *argv[])
{
countWord cw("1.txt");
return 0;
}
test:
1.txt:
China will stop accrediting foreign diplomas and
will degrees obtained via online courses starting
will from the spring semester this year as major overseas
study destinations have opened their borders,
according to the Ministry of Education's Chinese Service Center for Scholarly Exchange.
@
out:
Center
次数1 出现的行号有:5
China
次数1 出现的行号有:1
Chinese
次数1 出现的行号有:5
Education's
次数1 出现的行号有:5
Exchange
次数1 出现的行号有:5
Ministry
次数1 出现的行号有:5
Scholarly
次数1 出现的行号有:5
Service
次数1 出现的行号有:5
according
次数1 出现的行号有:5
accrediting
次数1 出现的行号有:1
and
次数1 出现的行号有:1
as
次数1 出现的行号有:3
borders
次数1 出现的行号有:4
courses
次数1 出现的行号有:2
degrees
次数1 出现的行号有:2
destinations
次数1 出现的行号有:4
diplomas
次数1 出现的行号有:1
for
次数1 出现的行号有:5
foreign
次数1 出现的行号有:1
from
次数1 出现的行号有:3
have
次数1 出现的行号有:4
major
次数1 出现的行号有:3
obtained
次数1 出现的行号有:2
of
次数1 出现的行号有:5
online
次数1 出现的行号有:2
opened
次数1 出现的行号有:4
overseas
次数1 出现的行号有:3
semester
次数1 出现的行号有:3
spring
次数1 出现的行号有:3
starting
次数1 出现的行号有:2
stop
次数1 出现的行号有:1
study
次数1 出现的行号有:4
the
次数2 出现的行号有:3 5
their
次数1 出现的行号有:4
this
次数1 出现的行号有:3
to
次数1 出现的行号有:5
via
次数1 出现的行号有:2
will
次数3 出现的行号有:1 2 3
year
次数1 出现的行号有:3