K&R2 1.5.4 example programme does not work


A

arnuld

this is "word counting" example programme from K&R2 section 1.5.4. it
runs without any error/warning but does not work properly, i.e.

the OUTPUT 1 should be:

NEWLINES: 1
WORDS: 1
CHARs: 5


the OUTPUT 2 should be:

NEWLINES: 4
WORDS: 4
CHARs: 21

--------------- PROGRAMME ---------------
/* K&R2 section 1.5.4

word counting

*/

#include <stdio.h>

#define IN 1
#define OUT 0

int main()
{
int c;
int nc = 0;
int nw = 0;
int nl = 0;

int state = OUT;

while((c = getchar() != EOF))
{
++nc;

if(c == '\n')
++nl;

if(c == ' ' || c == '\t' || c == '\n')
state = OUT;

else if(state == OUT)
{
++nw;
state = IN;
}
}

printf(" NEWLINES: %d\n WORDS: %d\n CHARs: %d\n", nl, nw, nc);

return 0;
}
----------------- OUTPUT 1 -------------
[[email protected] kr2]$ ./a.out
like
NEWLINES: 0
WORDS: 1
CHARs: 5
[[email protected] kr2]$

------------ OUTPUT 2 -------
[[email protected] kr2]$ ./a.out
like this

and this

NEWLINES: 0
WORDS: 1
CHARs: 21
[[email protected] kr2]$
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top