read from file and count same strings

I want to read from a file that contains strings and count how many strings of the same name are in the file. Number of strings on file is unknown. For example:

file.txt
--------
apple
apple
orange
red
red
red

output:
-------
file has:
apple 2
orange 1
red 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <map>
#include <string>


int main()
{
    std::map<std::string, int> dictionary;
    std::ifstream input("fruits.txt");
    std::string word;
    while (input >> word)
        dictionary[word]++;
    for(const auto& e: dictionary)
        std::cout << e.first << ": " << e.second << '\n';
}
I can't run it, it says e is not initialize
http://ideone.com/EZRixQ
Everything is working. Does your compiler has C++11 support turned on?
Last edited on
Don't think my IDE has it, I'm using visual studio 2010.

can it be implemented in way no to use c++11
sure it can be. Replace last loop with this:
1
2
for(std::map<srd::string, int>::const_iterator e = dictionary.begin(); e != dictionary.end(); ++e)
    std::cout << e->first << ": " << e->second << '\n';
Last edited on
great that worked! thank you.
Topic archived. No new replies allowed.