Re: good algorithms come with practice and reading good code/books?



August Karlstrom wrote:
Anyway, here is my version of the program:
Cool. Thanks for sharing it :)

#include <ctype.h>
#include <stdio.h>

int main(void)
{
int c, words = 0, chars = 0, insideword = 0;

c = getchar();
while (c != EOF) {
if (isspace(c)) {
Thanks I was unaware of isspace function.

if (insideword) { words++; }
insideword = 0;
I like the way you did it and yours works, my didn't. I was doing it
like this
if (nc > 0) ++nw;
nc = 0;
My version here did take care of multiple spaces in a row because nc
(number of characters in word) is only > 0 if it is the first
whitespace char (coming out of word, and nc is not set to 0 yet), but
it incorrectly incremented nw (new word) when first character of input
was a whitespace.

} else {
chars++;
insideword = 1;
}
c = getchar();
}
if (insideword) { words++; }
This catches when the last char is nonwhitespace and then EOF. My
version I didn't catch this.

printf("Found %d words and %d non-whitespace characters\n",
words, chars);
return 0;
}


August
Thanks again for sharing that.

.