If you want to be efficient and accomplish this in less possible amount of lines, but by using standard library, try this:
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <string>
int main()
{
std::ifstream f("text.txt");
std::istream_iterator<std::string> eof;
std::multiset<std::string> words( std::istream_iterator<std::string>(f) , eof);
std::ofstream f_out("text_output.txt");
for( std::multiset<std::string>::iterator i = words.begin(); i!=words.end(); i = words.upper_bound(*i) )
f_out << "the word " << *i << " found " << words.count(*i) << " times\n";
}
This code grabs the file named "text.txt" and outputs result to "text_output.txt"
Contents of "text.txt":
can can can I I I do this properly?
How many times do I need to program one thing to remember it?
Contents of "text_output.txt":
the word How found 1 times
the word I found 4 times
the word can found 3 times
the word do found 2 times
the word it? found 1 times
the word many found 1 times
the word need found 1 times
the word one found 1 times
the word program found 1 times
the word properly? found 1 times
the word remember found 1 times
the word thing found 1 times
the word this found 1 times
the word times found 1 times
the word to found 2 times
Good resource to learn fantastic ways of using c++ efficiently is a book called Accelerated c++.
Regards,