Re: K&R2 ex 1-8
From: CBFalconer (cbfalconer_at_yahoo.com)
Date: 10/16/04
- Next message: Kenny McCormack: "Re: Safer and Better C"
- Previous message: CBFalconer: "Re: Safer and Better C"
- In reply to: Merrill & Michele: "K&R2 ex 1-8"
- Next in thread: Mark McIntyre: "Re: K&R2 ex 1-8"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 15 Oct 2004 22:34:34 GMT
Merrill & Michele wrote:
>
> The following is my best attempt to solve the exercise in the
> subject line whose simple request is to write a program that
> counts blanks, tabs and newlines.
Which you should specify in the body, since subject lines are not
always visible when reading.
>
> #include <stdio.h>
> int main(int orange, char **apple)
> {
> int c,n1,n2,n3;
> n1=n2=n3=0;
> while((c=getchar()) != EOF)
> {
> if (c=='\n')
> ++n1;
> else if (c=='\t')
> ++n2;
> else if (c==' ')
> ++n3;
> }
> printf("%d %d %d\n",n1,n2,n3);
> return (0);
> }
It appears perfectly satisfactory, except it will needlessly
complain about unused parameters. In place of the obfuscated
parameter names, simply specify they are not supplied by using
void, and you can make the flow clearer by different formatting
(there are no prizes for paucity of blanks):
#include <stdio.h>
int main(void)
{
int c, n1, n2, n3;
n1 = n2 = n3 = 0;
while (EOF != (c = getchar())) {
if ('\n' == c) ++n1;
else if ('\t' == c) ++n2;
else if (' ' == c) ++n3;
}
printf("%d %d %d\n", n1, n2, n3);
return (0);
}
The formatting is purely a matter of style. The practice of
putting the constant first in equality tests makes it easier for
the compiler to pick up errors, because it can now detect the use
of '=' in place of '=='.
-- Chuck F (cbfalconer@yahoo.com) (cbfalconer@worldnet.att.net) Available for consulting/temporary embedded and systems. <http://cbfalconer.home.att.net> USE worldnet address!
- Next message: Kenny McCormack: "Re: Safer and Better C"
- Previous message: CBFalconer: "Re: Safer and Better C"
- In reply to: Merrill & Michele: "K&R2 ex 1-8"
- Next in thread: Mark McIntyre: "Re: K&R2 ex 1-8"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|