Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

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 82 views
1 answer 162 views
1 answer 173 views
1 answer 176 views
1 answer 176 views
1 answer 202 views
2 answers 176 views
...