Hello everyone, I am new and hope someone can help me! The problem I am working on is:
Code:
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.
Code:
#include <iostream>#include <string>
#include <fstream>
using namespace std;
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;
}