reading file and counting word appearances in it

Hello,

Getting on problem, where i'm trying to read input.txt which contains the following:
1
2
  colors red blue green yellow orange purple
sky blue high clouds air empty vast big


and output should be like:
1
2
3
4
5
(colors, black) => 1
(colors, blue) => 4 
.
.
.

Problem:
What i tried to do is, to take a file, and count number of word appearances in it.
Using online compiler : http://www.compileonline.com/compile_cpp11_online.php
My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <map> 
#include <fstream> 
#include <string> 
using namespace std;



template <class KTy, class Ty>
void PrintMap(map<KTy, Ty> map)
{
    typedef std::map<KTy, Ty>::iterator iterator;
    for (iterator p = map.begin(); p != map.end(); p++)
        cout << p->first << ": " << p->second << endl;
}

int main(void)
{
    static const char* fileName = "input.txt";


    map<string, unsigned int> wordsCount;


    {

        ifstream fileStream(fileName);


        if (fileStream.is_open())
            while (fileStream.good())
            {

                string word;
                fileStream >> word;


                if (wordsCount.find(word) == wordsCount.end()) 
                    wordsCount[word] = 1; 
                else 
                    wordsCount[word]++; 
            }
        else 
        {
            cerr << "Couldn't open the file." << endl;
            return EXIT_FAILURE;
        }

       
        PrintMap(wordsCount);
    }

    return EXIT_SUCCESS;
}

Kinda stucked after 4h looking at it :\


Thanks,
Michael
Last edited on
You did not tell what your problem is.
I see problem with typedef in your template:
It should be typedef typename std::map<KTy, Ty>::iterator iterator;
oh yes, after fixing it gettin error on 46th line of code saying that was not declared in that scopre.

well my problem is, this is not working somehow, and i dont know why :\ i mean, except that typedef error and this one now....

Edit:
On online compiler its working, but on codeblocks errors ;\ ( and i dont have internet everywhere )
Last edited on
Works for me: http://puu.sh/9fiSH/842dbdc824.png
Problem with line 46 (and 53) is that these macro are defined in cstdlib header. You can either include it or just use 0 for success and any non-zero value for failure
Last edited on
Okay, perfect. Thank you!
Best of Luck etcfantus. Keep the hard work going
Topic archived. No new replies allowed.