Word Counting from Array onto Output File

For this problem, I have to have two text files: one for list of words that need to be found and other containing the document that needs to be search. The results would placed in a output "results" file later on.

What I've Done: I've already figured out a way to store all of the word list onto an array and properly display it in the list.txt file.

Current Problem: How to find words that are the same and to increment the counter every time it is found. I've played around with the code but it still won't work.

Any help would be greatly appreciated!

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
   using namespace std;

   int main()
   {
      ifstream inFile1;
      ifstream inFile2;
      ofstream outFile;
   
      string wordList[100];
		string words;
		int wordCount = 0;
   
      inFile1.open("list.txt");
      if( inFile1.fail() )
      {
         cout << "Could not open input file - Aborting program!\n";
         exit(1);
      }
      else
      {
         for(int i = 0; i < 100; i++)
         {
            inFile1 >> wordList[i];
         }
      }
		
		outFile.open("results.txt");
		if( outFile.fail() )
    	{
        	cout << "Could not open output file - Aborting program!\n";
        	exit(1);
    	}
   
      inFile2.open("doc.txt");
		if( inFile2.fail() )
      {
         cout << "Could not open input file - Aborting program!\n";
         exit(1);
      }
		else
		{
		inFile2 >> words;
			for (int i = 0; i < 100; i++)
			{
				while(!inFile2.eof())
				{
					if(words == wordList[i]) wordCount++;
					inFile2 >> words;
				}
			}
		}
   	outFile << "-----------------------" << endl;
		outFile << "Word		Count" << endl;
		outFile << "-----------------------" << endl;
		for (int i = 0; i < 100; i++)
		{
  			outFile.width(2);
  			outFile << wordList[i] << endl;;
 		}
		outFile << wordCount;

		
      inFile1.close();
      inFile2.close(); // Close all files explicitly
      outFile.close();
      return 0;  
   }
Use a map:

http://www.cplusplus.com/reference/map/map/?kw=map

Line 15: map<string, int> wordCount;
Line 51: if(words == wordList[i]) wordCount[words]++;
Line 59:
1
2
3
4
5
for (map<string, int>::const_iterator i = wordCount.begin(); i != wordCount.end(); i++)
		{
  			outFile.width(2);
  			outFile << i->first << "         " << i->second << endl;;
 		}
Is there is a way to do this using parallel arrays instead of mapping?
Yes, make an int array with the same size as wordList (int wordCount[100] = { 0 };). Initialize it to 0 and increase it on line 51 like so wordCount[i]++;.

The output on line 62 would look like this:
outFile << wordList[i] << " " << wordCount[i] << endl;
Topic archived. No new replies allowed.