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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,699 questions

57,011 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 186 views
1 answer 260 views
1 answer 281 views
1 answer 264 views
1 answer 280 views
1 answer 330 views
2 answers 308 views
...