Re: some "newbie" questions

From: Les Cargill (lcargill_at_worldnet.att.net)
Date: 12/22/03


Date: Sun, 21 Dec 2003 23:12:57 GMT

Buck Rogers wrote:
>
> Hi guys!
>
> I've just bought The C Programming Language, K&R, 2nd Ed.
>
> I am having some trouble with the earlier excercises and some
> questions about the related sample programs. I've hunted through
> the FAQ, with no luck.
>
> ==========================================================
> 1. I've added int before main(), and return 0 to the below
> sample from p.17.
>
> #include <stdio.h>
>
> int main( void )
> {
> int c;
>
> while ((c = getchar()) != EOF)
> putchar(c);
>
> return 0;
> }
>
> Why does this program not end when I enter a blank line?
> It just keeps running until I press Ctr-C. Doesn't a
> blank line signify EOF? Will this program only end if
> Ctr-C is inputed by the user?
>

A blank line will not signify EOF. Try Ctrl-D or try Ctrl-Z.

> excercise 1-6: Verify that the expression getchar() != EOF is 0
> or 1.
>
> excercise 1-7: Write a program to print the value of EOF.
> =============================================================
>
> I've tried c = (getchar() != EOF) and then printing the value
> of c, which comes up with rubbish. I've spent a day on this and
> cannot answer the two above questions - logic is not my strong
> point. Any hints would be appreciated.
>

Try "printf("%c\n",EOF);" Other possibilities include
"printf("%d\n",EOF)" or "printf("%x\n",EOF);"

> ========================================================
> 2. I've added int before main(), and return 0 to the below
> sample from p.18.
>
> int main( void )
> {
> double nc;
>
> for (nc = 0; getchar() != EOF; ++nc)
> ;
> printf("%.0f\n", nc);
>
> return 0;
> }
> ============================================================
>
> I personally would have used nc++, but the book reckons the
> results would be the same. Anyway, why does the above sample
> not increment the value of nc in any way? All the program
> does is keep on accepting values that I type in ie.
>
> 5
> 6
> 7
> ajalal
>
> The program ends when I press Ctr-C.
>

When you press Ctrl-C, this generates an interrupt that causes
the program to abort. It never gets to the line with the printf.

Try Ctrl-D or Ctrl-Z to trigger the EOF condition.

> I don't know if C has changed so much from when the book was
> written that I actually need to radically modify the samples to
> achieve what they were meant to achieve.
>
> I am also somewhat an advanced newbie(ie. I've read other C texts cover
> to cover), so getting stuck so early in this book really puts me in my
> place. However I am determined to do each and every excercise.
>
> Thanks in advance!
>
> Buck
>
> --
> Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/

--
Les Cargill