Could anyone possibly help...?

Hello. I am working on a program that needs to, using a map, count every time a word occurs in a text document. The real issue that I am facing is how to read in the words from the text file. I understand the std::ifstream, I just don't know how to 'use' it. Any help on how to take in the text file and count the words would be great. Again, thanks!!
You can use it with the extraction operator, that is operator>>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <string>
#include <map>
#include <iostream>

int main()
{
    std::ifstream file("test.txt");
    std::map<std::string, unsigned> m;
    for(std::string word; file >> word; )
        ++m[word];

    for(auto& p: m)
        std::cout << "The word '" << p.first << "' was found " << p.second << " times\n";
}

What does ('auto& p': m) mean? I know that it is something that everyone keeps referencing in a few of my classes but I have never really looked into using it. Is it something along the lines of a generic? Or something entirely different?
Just a loop going over every element of a container. There are several ways to write that, this is the simplest.
So, its like an iterator? Just without all the excess typing?
I also have one last question:
With every word that I take in, is their a way that I can make sure that every character in the word is lower case? Isn't their something in the stl that does that for me?
sure, there are plenty of ways to lowercase every letter of a word:

loop (range-for, iterator-based, or indexed, e.g.)
1
2
for(auto& c: word)
    c = std::tolower(c);


for_each
std::for_each(word.begin(), word.end(), [](char& c){ c = std::tolower(c); });

transform, which might be a bit wordy:
1
2
 std::transform(word.begin(), word.end(), word.begin(),
                  [](char c){return std::tolower(c); });
or, 1998 textbook style,
1
2
    std::transform(word.begin(), word.end(), word.begin(),
                   static_cast<int(*)(int)>(std::tolower));


or even the rarely-used ctype:
std::use_facet<std::ctype<char>>(std::locale()).tolower(&word[0], &word[0] + word.size());

finally, there's always boost:
boost::algorithm::to_lower(word);

which could be incorporated in that program I first wrote in its to_lower_copy version:

1
2
   for(std::string word; file >> word; )
        ++m[boost::algorithm::to_lower_copy(word)];

Topic archived. No new replies allowed.