I am having an issue with the strtok in my program. It doesn't seem to be matching the delimiters correctly.
My program is supposed to count the number of words (working) and number of sentences in a text file. My text file has 271 words and 5 sentences. A sentence is defined as a single period '.' in the file. A word is simply ended followed by a blank space ' ' in the file.
My text file has 5 instances of '...' yes three periods in a row. Even if I count each '...' as 3 I should only have a count of 20 sentences in my file. The program keeps showing 35 sentences.
As you can see in my code I played with the idea of strstr to find '...' and reduce my count by 3 each time, but this didn't work out either.
Here is my code:
Code:
#include <stdio.h>#include <string.h>
int main(int argc, char* argv[])
{
int words = 0;
int sentences = 0;
char str[200];
char * test;
FILE *fp;
//Read in File
fp = fopen("test.txt", "r");
if(!fp) return 1; // ends program if file is not found
while(fgets(str,sizeof(str),fp) != NULL){
// gets rid of the trailing '\n' (if it is there)
int len = strlen(str)-1;
if(str[len] == '\n')
str[len] = 0;
// Split string into tokens (found on cplusplus.com website)
// used to count number of words
test = strtok (str," .");
while (test != NULL) {
test = strtok (NULL, " ");
++words;
}
test = strtok (str,".");
while (test != NULL) {
test = strtok (NULL, ".");// still need to skip '...' ???
++sentences;
if(test == "..."){
sentences = sentences - 3;
}
}
//test = strstr (str,"...");
//while (test != NULL) {
// test = strstr (str,"...");
// sentences = sentences - 3;
//}
}
//Print out Results
printf("Results:\n");
printf("\n\nNumber of Words: %d\n", words);
printf("Number of Sentences: %d\n", sentences);
fclose(fp);
getchar();
}
Thanks for any help on this!!