Vote count: 0
I have been trying to do a program that will count the number of words from a text file. I have been having problem with counting the words, I decided to create a function to do so because I will do other things with this program (I really want to create a text editor, but I am doing so piece by piece).
The problem is:
My program returns an enormous amount of counted words when I know the text file has a much lower word count. What I am really trying to learn here is how to iterate through characters in an array of strings[I][J].
Additional information:
- The function that does the counting can print all the strings if I do a simple loop to print all the strings. That means it has passed the strings correctly.
- I am sending the correct number of lines to the function, I have already double checked.
Here is my code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 10000
int main (int argc, char *argv[]) {
int i = 0;
int j = 0;
char content[MAX_LEN + 1];
int totalWords = 0;
int sentence = 0;
int syl = 0;
int totalLines = 0;
char **strings;
FILE *fp;
strings = malloc (sizeof(char *) * totalLines);
if (strings == NULL) {
printf("Error: allocation failed\n");
exit(0);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error opening file, file pointer is null\n");
printf("Please try again with a new file\n");
exit(0);
}
while(fgets(content, MAX_LEN, fp) ) {
content[strlen(content) -1] = '\0';
strings[i] = malloc ((sizeof(char*)) * (strlen(content)) +1 );
strcpy(strings[i], content);
i++;
totalLines++;
strings = realloc(strings, sizeof(char *) * (totalLines ) + 1 );
if (strings == NULL) {
printf("Error: memory reallocation failed\n");
exit(0);
}
}
totalWords = fWords(strings, totalLines);
printf("%d is the total of words\n", totalWords);
for (j = 0; j <= totalLines; j++) {
free (strings[j]);
}
free(strings);
strings = NULL;
fclose(fp);
return 0;
}
int fWords (char **array, int index) {
int number;
int i = 0;
int in = 0;
int j = 0;
int length = 0;
while (i < index) {
length = strlen (array[i]);
for (j = 0; array[i][j] <= length; j++) {
if (isspace(array[i][j]) != 0) {
in = 0;
}
else if (in == 0) {
in = 1;
number++;
}
}
i++;
}
return number;
}
asked 17 secs ago
c program not counting words properly
Aucun commentaire:
Enregistrer un commentaire