counting input words

A

arnuld

any comments for improvement:

/* C++ Primer - 4/e
*
* CHAPTER 10 - Associative Containers
*
* EXERCISE - 10.7
* Write a program to count and print the number of times each word
* occured in the input.
*
*/


#include <iostream>
#include <string>
#include <vector>
#include <map>

int main()
{
std::map<std::string, int> word_count;
std::string aword;
while( std::cin >> aword )
{
++word_count[aword];
}


std::cout << "\n----------------------------------------------------\n";
for( std::map<std::string, int>::const_iterator iter =
word_count.begin();
iter != word_count.end(); ++iter )
{
std::cout << iter->first << " occured "
<< iter->second << " times "
<< std::endl;
}

return 0;
}

================= OUTPUT =======================

/home/arnuld/programs $ ./a.out
bazarov
Jack
Bux
Bux
Bazaro
Jack
Bux

----------------------------------------------------
Bazaro occured 1 times
Bux occured 3 times
Jack occured 2 times
bazarov occured 1 times
/home/arnuld/programs $
 
J

James Kanze

arnuld said:
any comments for improvement:
/* C++ Primer - 4/e
*
* CHAPTER 10 - Associative Containers
*
* EXERCISE - 10.7
* Write a program to count and print the number of times each word
* occured in the input.

Well, the obvious question is: how do you define a word? I'd
say that this should be documented. (For purposes of learning,
what you've done is actually quite good. But it certainly
doesn't define word in the usual English language sense.)
*
*/


#include <iostream>
#include <string>
#include <vector>
#include <map>

int main()
{
std::map<std::string, int> word_count;
std::string aword;
while( std::cin >> aword )
{
++word_count[aword];
}

The one thing I'd do differently (but again, it's probably not
necessary in an exercise): I'd use a class instead of int as the
counter. A class which checked for overflow, and gave defined
behavior in that case.

I might also use a class Word, to facilitate changing its
definition (although it would start as a trivial wrapper for
std::string).

Both of these concepts are related to more industrial
considerations, though, and aren't necessarily relevant in a
learning context.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Chatbot 0
CIN Input #2 gets skipped, I don't understand why. 1
counting words in input 16
sort input 7
counting repeated words in input 10
problem with iterator (map iterator) 3
TF-IDF 2
C++ Primer ex 3.14 8

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top