down

Richard A. O'Keefe ok at quintus.uucp
Tue Dec 13 19:43:13 AEST 1988


In article <45476 at yale-celray.yale.UUCP> wald-david at CS.YALE.EDU (david wald) writes:
>In article <843 at quintus.UUCP> ok at quintus.UUCP (Richard A. O'Keefe) writes:
>>       for (chcnt = 0; (c = getchar()) != EOF; chcnt += c == '\n' ? 2 : 1)
>>           ;
>
>Urgh.  Yes, it's not *too* unreadable, yes it's correct, but if you're
>going to do it like that, why bother eliminating the while loop:

But I *didn't* eliminate any "while" loop.  I started again from scratch
and observed that the point of the loop is to maintain chcnt, and a "for"
loop was the appropriate structure.

In fact, the way I would be inclined to do this is a wee bit more general:
	char chlen[256];

	for (c = sizeof chlen; --c >= 0; )
	    chlen[c] = 1;
	chlen['\n'] = 2;

	for (chcnt = 0; (c = getchar()) != EOF; chcnt += chlen[c])
	    ;

The advantage of this is that you can also add
	chlen['\r'] = 0;
so that the same result will be obtained from a file which already has
CRLF pairs as from one which has single LFs.



More information about the Comp.lang.c mailing list