Instead of the simple if(char == space) logic, (which obviously can't handle multiple spaces), how about this.
inword = 0; changes to inword=1 when you find a word. When you leave a word, it goes back to 0.
First letter you run across, you set it to 1, and increment word counter. When you run into the first space, you set it to 0, and do not increment word count any more, until you run into the next letter.
You need to add some logic to handle things like the last word in a sentence, at the end of a file, etc.
Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
Not yet - that's the same logic as before, using different variables. :(
in the header file ctype.h, we have functions to test what kind of char it is. I'd use two of them, so include at the top of your program.
Those two are ispunct() (is it a punctuation, and isalpha(), is it a regular alphanumberic char (letter or number)?
So the logic will be (approximately):
if((inword equals 0) and (isalpha(char being checked))) { //
inword = 1
wordcount increments by one
}
/* handles last word in a row which has no space after it. */
else if(char equals ' ' or !isalpha(char being checked)) {
inword = 0
}
May be more logic needed, but not much. It's been a long time since I coded one up. Give this a try, and post back up and I'll study it more.
Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
Edit: this seemed to work OK, in my very limited testing.
fp is the file pointer, ch is a char, and the other variables are int's. ctype.h was included, of course.
while((ch=getc(fp)) != EOF) {
putchar(ch);
if((isalpha(ch)) && (inword==0)) {
inword=1;
wordcount++;
}
else if(!isalpha(ch)) { //isalpha(ch)==0
inword=0;
}
}
fclose(fp);
printf("\n I counted %d words in that file\n", wordcount);
Give this a try, and if no luck, post back, but I think you'll get it from this.
Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
By the way, isalpha() only checks for Letters, isalnum() checks for Letters and Digits..
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944