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



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
.



Relevant Pages

  • Re: good algorithms come with practice and reading good code/books?
    ... Kernighan & Richie on my own time (I'm not a programmer but I want to ... //program that counts the number of words and total chars ... int c; //var that holds char read from stdin ... int tnc; //counts total chars minus any whitespace, ...
    (comp.lang.c)
  • good algorithms come with practice and reading good code/books?
    ... I am a newbie and going through "The C programming language" by ... //program that counts the number of words and total chars ... int c; //var that holds char read from stdin ... int tnc; //counts total chars minus any whitespace, ...
    (comp.lang.c)
  • creating a testfile for catv
    ... control chars and non-ascii chars: ... int main ... void filecopy ... Am I correct to think that the first 32 chars are control chars? ...
    (comp.lang.c)
  • Re: Character Operators
    ... the chars are promoted to ints and so the difference between two chars is an int. ... The code you posted wouldn't be used except in converting characters to numerics. ... It has everything to do with the numerical base being used, and hexadecimal is the only commonly used numerical base that includes letters as digits. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Strange way to convert char to int (?)
    ... >> chars are automatically promoted to ints before doing arithmetic. ... >> This is a fast way of converting a single char digit to binary int. ... I think this is bad way to convert characters to the numbers they ... since this is game, the code should be very fast. ...
    (comp.lang.java.programmer)