私は、テキストファイル内のユニークな単語を数えるワードカウンタを作成する必要があるプロジェクトに取り組んでいます。授業ではSTLについて学んだだけで、地図を使ってプログラムを作成することになっています。私がファイルから単語を読み込んで正確に数えますが、必要な記号や数字は無視されません。たとえば、今のように、単語 "ファイル"と "ファイル"を数えます。 2つの別々の単語として。どうすれば修正できますか?もう1つの問題は、単語をアルファベット順に印刷することです。これは私がこれまで持っていたものです。C++文字列に読み込むときに、テキストファイルのシンボル/数値を無視するにはどうすればよいですか?
#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;
}