HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Counting word occurences

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wordcountingoccurences

Problem

This is a simple word count program I wrote to play around and get familiar with using std::map. Is there anything I can improve upon?

I didn't use CTRL+Z to stop the program because that suspends the process on Linux.

#include 
#include 
#include 
#include 
#include 
using std::cout;
using std::cin;
using std::endl;
using std::string;

int main(){
    std::map words;
    cout  begin(cin);
    std::istream_iterator end;

    while(begin != end){
        if(*begin == string("***"))
            break;
        words[*begin++]++;
    }
    for(std::map::iterator iter = words.begin(); iter != words.end(); ++iter)
        cout second first << endl;

return 0;
}


Sample input:

engie does wut engie wants
pyro mad  
engie rek pyro
pyro go cry
deny engie u try
rekt u will get


Output:

1 cry
 1 deny
 1 does
 4 engie
 1 get
 1 go
 1 mad
 3 pyro
 1 rek
 1 rekt
 1 try
 2 u
 1 wants
 1 will
 1 wut

Solution

You cannot use double quotes in a string literal like this:

cout << "Enter some text. Type "***" to end." << endl;


(The syntax-highlighting even changes the color of the ***.)

In order to print them out, you have to escape them as such:

cout << "Enter some text. Type \"***\" to end." << endl;


I suppose your compiler ignored the original, as I got an error when I tried it.

See this for more info on escape sequences in C++.

Code Snippets

cout << "Enter some text. Type "***" to end." << endl;
cout << "Enter some text. Type \"***\" to end." << endl;

Context

StackExchange Code Review Q#64571, answer score: 6

Revisions (0)

No revisions yet.