I have an exercise says:
Write a program that reads input as a stream of characters until encountering EOF. Have it report the average number of letters per word. Don't count whitespace as being letters in a word. Actually, punctuation shouldn't be counted either, but don't worry about that now. (If you do want to worry about it, consider using the ispunct() function from the ctype.h family.)
I wrote this code for the solution:
Code:
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
int main(void)
{
int c;
bool inword = false;
int w_count = 0, c_count = 0;
while ((c=getchar())!= EOF)
{
if (isspace(c) && !inword)
continue;
if(!isspace(c) && !inword)
{
inword = true;
w_count++;
}
if(isspace(c) && inword)
inword = false;
if(!isspace(c))
c_count++;
}
printf("chars = %d\nwords = %d\n", c_count, w_count);
printf("avg num of letters per word = %d\n", c_count/w_count);
return 0;
}
is it right (I didn't care about punctuation)? if something wrong, could you explain why?
Thank you very much.