Hello funs2code!
I have the following problem. I need to count the number of occurrences of a concrete word in a text file. I've tried to count the number of occurrences of each word at first.
The following code has no errors but it isn't working! When I type in a command line "project1.exe test.dat cat dog cat dog" the empty string is showed. I've cheked if-statements -> right working. Then I've made a conclusion that problem is in for-statement (with iterators). Can anyone explain me, guys?
#include <iostream.h>
#include <fstream.h>
#include <map.h>
#include <string.h>
#include <iterator.h>
typedef std::map<std::string, int> StrIntMap;
void countWords(std::istream& in, StrIntMap& words) {
std::string s;
while (in >> s) {
++words[s];
}
}
using namespace std;
int main(int argc, char** argv) {
if (argc < 2) {
printf("\nNot correct input");
return(EXIT_FAILURE);
}
ifstream in(argv[1]);
if (!in) {
printf("\nFile ");
printf(argv[1]);
printf(" is not found");
exit(EXIT_FAILURE);
}
StrIntMap w;
countWords(in, w);
for (StrIntMap::iterator p = w.begin( );
p != w.end( ); ++p) {
std::cout << p->first << " occurred "
<< p->second << " times.\n";
}
}