I am to use "C-strings, not C++ string objects" per teacher to read a paragraph from an input file and count characters, words, sentences, and the number of to-be verbs (to, be, am, are, is, was, were). My current program clears compiler but my character count and words count both off by two. My code to count sentences stops after counting one sentence. Any help as to my errors is appreciated. Still working to debug. My teacher basically told the class what strtok
did and then literally told us to figure it out from there. Not asking for you to do it for me -- just tips/hints to get back in the right direction. Happy Easter.
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib>
using namespace std;
const int MAX_FILENAME = 256;
//Longest word length = 15 chars
const int MAX_WORD_CHARS = 16;
//Longest word in paragraph = 200 words
const int WORDS_MAX = 200;
//Max amount of chars in paragraph = 15*200
const int MAX_PARAGRAPH_CHARS = 3000;
//Max chars in a sentence
const int MAX_SENTENCE_CHARS = 200;
const int MAX_SENTENCES = 25;
const int NUM_TO_BE_VERBS = 5;
void readParagraph( ifstream& input, char [] );
int countWords( char [], char tp[][MAX_WORD_CHARS] );
int countSentences( char [] );
int main()
{
int i;
int words, sentences, average;
char filename[MAX_FILENAME];
ifstream input;
//Holds paragraph characters
char p[MAX_PARAGRAPH_CHARS];
const char TO_BE_VERBS[NUM_TO_BE_VERBS][MAX_WORD_CHARS] = { "am", "are", "is", "was", "were" };
const char BE[] = "be";
const char TO[] = "to";
char tp[WORDS_MAX][MAX_WORD_CHARS];
//Prompt user input file name
cout << "Enter input file name: ";
cin.get( filename, 256 );
//Open input file
input.open( filename );
//Check input file exists
if ( input.fail() )
{
cout << "Input file " << filename << " does not exist." << endl;
exit(1);
}
//Reads paragraph into array
readParagraph( input, p );
countWords( p, tp );
countSentences( p );
return(0);
}
void readParagraph( ifstream& input, char p[] )
{
int count = 0;
while ( input.get( p[count]) && (count < MAX_PARAGRAPH_CHARS) )
{
count++;
}
p[count - 1] = '\0';
cout << "Number of characters: " << count << endl;
}
int countWords( char p[], char tp[][MAX_WORD_CHARS] )
{
int i = 0;
char* cPtr;
cPtr = strtok( p, " " );
while ( cPtr != NULL )
{
strcpy( tp[i], cPtr );
i++;
cPtr = strtok( NULL, " " );
}
cout << "Number of Words: " << i << endl;
return(i);
}
int countSentences( char p[] )
{
int j = 0;
char* Ptr;
char sent[25];
Ptr = strtok( p, ".!?" );
while ( Ptr != NULL )
{
strcpy( sent, Ptr );
j++;
Ptr = strtok( NULL, ".!?" );
}
cout << "Number of sentences: " << j << endl;
return(j);
}