Help with counting problem

Hello everyone, I am new and hope someone can help me! The problem I am working on is:

1
2
3
4
5
6
Write a C++ program that reads several lines of text from a file and prints a table indicating the number of occurrences of each different word in the text. Also, your program should include the words in which they appear in the text. For example, the lines
 
To be, or not to be: that is a question:
Whether 'tis nobler in the mind to suffer”

contains the words "to" three times, the word "be" two times, the word "or" once, etc.  


This is what I have so far! It seems to run fine if I use cin >> string;, but once i load it from the file, the output i get is :

to - 1
be, - 1
or - 1
ect.

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
72
73
74
75
76
77
78
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int MAX_CHARS_PER_LINE = 512;
const int MAX_TOKENS_PER_LINE = 20;
void number_of_words(char words[] );

int main()
{

	 ifstream inData;
	ofstream outData;
	inData.open("sentences.dat");
	 if (!inData.good()) 
    return 1; // exit if file not found
	outData.open("results.dat");
	char string[100];
	while(!inData.eof())
	{
		inData.getline(string,100);
		number_of_words(string);
		
	}
	return 0;
	inData.close();
}

void number_of_words( char words[] )
{
	// Variable declaration.
	 // Variable declaration.
      char *ptr[25], *token;
      int counter[25], i = 0, test = 0;

      // initialize each element of counter to 1.
      for( int a = 0; a < 25; a++ ) {
		  counter[a]=1;
	  }

      // get a token from string
      token = strtok( words , " ,;" );
      // assigns the token to 0th element of array.
      ptr[0] = token;
      token = strtok( NULL, " ,;" );

      while( token != NULL )
      {
             for( int j = 0; j < i+1; j++ )
             {
                    test = 0;

                    int compare = strcmp(ptr[j], token);
                    // if this token is already count then increment it.
                    if( compare == 0 )
                    {
                           counter[j]++;
                           test++;
                           break;
                    }

             }

             // if this token is not yet found, then assign it to a new element
             if( test == 0 )
             {
                    i++;
					
                    ptr[i] = token;
             }

             token = strtok( NULL, " " );
      }
      
      for( int a = 0; a < i+1; a++ )
             cout << ptr[a] << "   " 
                  << counter[a] << " times." << endl;
}
Topic archived. No new replies allowed.