【发布时间】:2018-04-04 17:49:45
【问题描述】:
我正在做一个项目,我需要制作一个单词计数器来计算文本文件中的唯一单词。在课堂上,我们刚刚学习了 STL,我们应该使用地图制作程序。我从文件中读取的单词并准确计算它们,除了它不会忽略符号或数字,这是我需要它做的。例如,就像现在一样,它计算单词“file”和“file”。作为两个单独的词。我该如何解决?我遇到的另一个问题是单词应该按字母顺序打印。这是我目前所拥有的。
#include <iostream>
#include <map>
#include <fstream>
#include <string>
using namespace std;
template <class words, class counter>
void PrintMap(map<words, counter> map)
{
typedef std::map<words, counter>::iterator iterator;
for (iterator p = map.begin(); p != map.end(); p++)
cout << p->first << ": " << p->second << endl;
}
int main()
{
static const char* fileName = "D:\\MyFile.txt";
map<string, int> wordCount;
{
ifstream fileStream(fileName);
if (fileStream.is_open())
while (fileStream.good())
{
string word;
fileStream >> word;
if (wordCount.find(word) == wordCount.end())
wordCount[word] = 1;
else
wordCount[word]++;
}
else
{
cerr << "Couldn't open the file." << endl;
return EXIT_FAILURE;
}
PrintMap(wordCount);
}
system("PAUSE");
return 0;
}
【问题讨论】:
标签: c++ string dictionary count words