Never, ever use gets()
. It's accessible to you at all only because C library purveyors prefer to avoid breaking legacy programs that rely on it. Prefer fgets()
or [f
]scanf
. Or in some cases, fread
might be as good.
You are counting words as the number of word separators. This will ordinarily result in a count that is one too few, because it effectively ignores the first word. In your particular case, it will also miss counting if there is a sentence separator that is not accompanied by a word separator. I suggest instead counting transitions from non-word to word, where non-word includes not only word separators, but also sentence separators. That would also fix the problem of mis-counting words if multiple separators appear in a row.
Your scanf()
call will ignore leading whitespace, and stop reading at the first whitespace it finds afterward. This will totally screw up your word counts for multiline inputs, and your sentence counts as well (since newlines are whitespace and therefore will be ignored). fgets()
would be a better choice.
You don't need to update the average every time you meet a new line, and that will give you the wrong result in the event that the input ends in the middle of a line. You should probably just wait until the whole input has been read, then compute the average.
You are recalculating the length of the input string every time you test i < strlen(words)
. Unless your compiler happens to optimize that for you, it is dreadfully inefficient. Instead, either pre-compute the length, once per line, or test instead whether you have reached the string terminator (for example, words[i] != '\0'
).
Your sentence count will be wrong (arguably) if a newline is entered after a period -- it will count two sentences, one with zero words. You could consider detecting this and correcting it, but maybe the grader will assume that you should not.
An if
/ else
tree with all the conditions testing for specific values of the same object is probably a tiny bit less efficient than a switch
statement. IMO, the switch
is easier to read, too.
You say you want to compute the average number of words per line but you are actually computing the number per sentence. Your specifications say that you are to counting line breaks as sentence breaks, but as far as I can see, they don't say the reverse, and that would not be a natural reading.
You don't need stdlib.h
for what you show. Nor string.h
if you take out the strlen()
call. You do, however, need stdio.h
, and you're not including it.