Re: good algorithms come with practice and reading good code/books?
- From: August Karlstrom <fusionfive@xxxxxxxxx>
- Date: Sat, 30 Dec 2006 15:48:03 GMT
vlsidesign skrev:
[...]
Here is my program by the way:
#include <stdio.h>
//program that counts the number of words and total chars
// but without whitespace, and newlines
// tracks going in/out of words for purpose of counting
#define IN 1 //inside a word
#define OUT 1 //outside a word
You probably want the constants to have distinct values.
main ()
Should be `int main(void)'.
{
int c; //var that holds char read from stdin
int state; //flag for in/out of words
I would use a boolean variable `int insideword' or `bool insideword' (after including stdbool.h) instead. It will make the program both clearer and shorter.
Anyway, here is my version of the program:
#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)) {
if (insideword) { words++; }
insideword = 0;
} else {
chars++;
insideword = 1;
}
c = getchar();
}
if (insideword) { words++; }
printf("Found %d words and %d non-whitespace characters\n",
words, chars);
return 0;
}
August
.
- Follow-Ups:
- Re: good algorithms come with practice and reading good code/books?
- From: vlsidesign
- Re: good algorithms come with practice and reading good code/books?
- References:
- good algorithms come with practice and reading good code/books?
- From: vlsidesign
- good algorithms come with practice and reading good code/books?
- Prev by Date: Re: without loop printing 1 to n
- Next by Date: Re: c / c++ : is it end of era ?
- Previous by thread: good algorithms come with practice and reading good code/books?
- Next by thread: Re: good algorithms come with practice and reading good code/books?
- Index(es):
Relevant Pages
|