read multiple text files and count the occurrences of a word

I am supposed to read(scan) data from a folder with multiple(21578) text files, and file names are numbered from 1 to 21578,and read each word that occurs in a text file, and count the number of times it occurs in the entire folder,i.e; in all the files how do i go about it? Plz help.

i've tried this so far..but it isn't working..

#include <iostream>
#include <map>
#include <string>
using namespace std;

void incrementString(map<string, int> &theMap, string &theString) {
if(theMap.count(theString)) {
theMap[theString]++;
} else {
theMap[theString] = 1;//This fixes the issue the other poster mentioned, though on most systems is not necessary, and this function would not need an if/else block at all.
}
}

void printMap(map<string, int> &theMap) {
map<string, int>::iterator it = theMap.begin();

do {
cout << it->first << ": " << it->second << endl;
} while(++it != theMap.end());

}

int main() {
map<string, int> stringMap;

for(int i=1;i<21578;i++)
{
string x;
ifstream inFile;

inFile.open(i+".txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}

while (inFile >> x) {
cout << x << endl;
}

inFile.close();



incrementString(stringMap, x);//Adding one occurance



printMap(stringMap); //Printing the map so far
}}

int main_alt() {
map<string, int> stringMap;

string someString;

while(cin>>someString) {//reads string from std::cin, I recommend using this instead of getline()
incrementString(stringMap, someString);
}

printMap(stringMap);
}
> inFile.open(i+".txt");

i is an int, not a std::string.

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
#include <map>
#include <fstream>
#include <string>
#include <sstream> // for C++98

std::map< std::string, int >& insert_from_file( std::map< std::string, int >& wc,
                                                  const std::string& path )
{
    std::ifstream file(path) ;
    std::string word ;
    while( file >> word )
    {
        // sanitise the word - take care of punctuation etc.
        ++wc[word] ;
    }
    return wc ;
}

int main()
{
    const int last_file_number = 21578 ;
    const char* const ext = ".txt" ;

    std::map< std::string, int > wc ;

    for( int fn = 1 ; fn <= last_file_number ; ++fn )
    {
        insert_from_file( wc, std::to_string(fn) + ext ) ; // C++11

        // C++98
        // std::ostringstream stm ;
        // stm << fn ;
        // insert_from_file( wc, stm.str() + ext ) ;
    }
    
    // use the map
}
Topic archived. No new replies allowed.