while( (ch = fgetc( infile )) != EOF )
if(ch ==' ') words++;
It works nice, but in case if we have blank lines in a string, how are we suppose to detect these lines and to count thw words right?
while( (ch = fgetc( infile )) != EOF )
if(ch ==' ') words++;
It works nice, but in case if we have blank lines in a string, how are we suppose to detect these lines and to count thw words right?
Your code does not count words, it counts spaces. In many cases the two counts would be different - for example, when words are separated by more than one space.
You need to change the logic in such a way that you set a boolean flag "I'm inside a word" when you see a character that belongs to a word, and has the following logic when it sees a whitespace character (a space, a tab, or a newline character):
if (isspace(ch)) {
if (sawWordFlag) {
words++;
sawWordFlag = false;
}
}
One way to detect if a character belongs to a word is to call isalnum
on it. Both isalnum
and isspace
functions require you to include <ctype.h>
header.
So sscanf
already does what you need, it will eat any number of whitespaces before a string including tabs and newlines. This algorithm works with leading or trailing spaces as well.
int words = 0;
int i = 0;
while(sscanf(inFile, "%*s%n", &i) != EOF){
inFile += i;
words++;
}
sscanf
is extremely versatile you can easily read out each word as follows:
int words = 0;
int size = strlen(inFile);
if(size > 0){
char* word = (char*)malloc((size + 1) * sizeof(char));
for(int i = 0; sscanf(sentence, "%s%n", word, &i) > 0; sentence += i){
// Do what you want with word here
words++;
}
free(word);
}
char prev = 'x'; // anything but space
while((ch == fgetc(infile)) != EOF)
{
if(ch == ' ' && ch == prev)
continue;
else if(ch == ' ' && ch != prev)
words++;
prev = ch;
}