How to count occurrences of each word in a text file with C++

1 Answer

0 votes
#include <iostream>
#include <fstream> 
#include <map>
#include <string> 

using std::cout;
using std::endl;
using std::map;
using std::string;

template <class Word, class Counter>
void PrintMap(map<Word, Counter> map) {
	typedef std::map<Word, Counter>::iterator it;

	for (it m = map.begin(); m != map.end(); m++)
		cout << m->first << ": " << m->second << endl;
}

int main(void)
{
	static const char *fileName = "d:\\data.txt";

	map<string, unsigned int> wordsCounter;
	{
		std::ifstream ifs(fileName);

		if (ifs.is_open()) {
			while (ifs.good()) {
				string word;
				ifs >> word;

				if (word != "") {
					if (wordsCounter.find(word) == wordsCounter.end())
						wordsCounter[word] = 1;
					else
						wordsCounter[word]++;
				}
			}
		}
		else  {
			std::cerr << "Error open the file" << endl;
			return EXIT_FAILURE;
		}
		PrintMap(wordsCounter);
	}

	return EXIT_SUCCESS;
}

/*
run:

c: 1
c#: 1
c++: 3
java: 1
php: 1
python: 1

*/

 



answered Jun 15, 2018 by avibootz

Related questions

1 answer 109 views
1 answer 185 views
1 answer 203 views
1 answer 197 views
1 answer 199 views
1 answer 229 views
2 answers 199 views
...