By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,911 Members | 1,171 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,911 IT Pros & Developers. It's quick & easy.

K&R2 1.5.4 example programme does not work

P: n/a
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 -------------
[arch@voodo kr2]$ ./a.out
like
NEWLINES: 0
WORDS: 1
CHARs: 5
[arch@voodo kr2]$

------------ OUTPUT 2 -------
[arch@voodo kr2]$ ./a.out
like this

and this

NEWLINES: 0
WORDS: 1
CHARs: 21
[arch@voodo kr2]$

Mar 20 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Mar 20, 6:19 pm, "arnuld" <geek.arn...@gmail.comwrote:
while((c = getchar() != EOF))
this was the BUG, it should be:

while((c = getchar()) != EOF)

sorry for bothering you

Mar 20 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.