Reputation: 13
#include <stdio.h>
#include <ctype.h>
int main (){
int ch;
unsigned long int charcount=0;
unsigned long int wordcount=0;
unsigned long int linecount=0;
while((ch=getchar())!=EOF){
if (ch!=' '&& ch!='\n'){
charcount++;
}
if(ch==' '|| ch=='\n'){
wordcount++;
}
if (ch=='\n'){
linecount++;
}
}
printf( "%lu %lu %lu\n", charcount, wordcount, linecount );
return 0;
}
The question is: a C program called that counts the number of characters, words and lines read from standard input until EOF is reached. Words are defined as contiguous sequences of letters (a through z, A through Z) and the apostrophe ( ', value 39 decimal) separated by any character outside these ranges. Lines are defined as contiguous sequences of characters separated by newline characters ('\n'). Characters beyond the final newline character will not be included in the line count.
For most cases it counts the number of words correctly, but I don't think my condition for wordcount is correct
Upvotes: 0
Views: 227
Reputation: 63481
Your program is not correctly handling word separators. Instead, it contains the assumption that any word separator marks the end of a word. So it is counting a word even when no word has started.
There are many ways you might approach this, but the general idea is to maintain some kind of state which represents that you are either in a word, or you are between words.
Here is one such example:
int wordcount = 0;
int betweenwords = 1;
while((ch=getchar())!=EOF)
{
if (!isspace(ch)) {
wordcount += betweenwords;
betweenwords = 0;
}
else {
betweenwords = 1;
}
}
This doesn't follow the same criteria for a word as your program (mine is treating all non-space characters as words), but it would be quite simple to adapt. The point here is to understand that you can use some kind of state variable to determine whether to increment your word count or not. In my example, the state variable is also used as the increment.
Upvotes: 2