Darklight <> writes:
> Question the program below is taken from a book which i have been
> told is bad, but it gives me the basics which is what i need, and
> yes i know the gets function should not be used, but i would like
> to see how other people would get the program below to work.
>
> I have already got it to work by changing some thing in the
> typedef struct, but i would like to see how the more experienced
> programmer would get it to work
>
> The program is used to demonstrate "unions in structures"
> the book it's taken from is "c programming in easy steps"
Amazon shows a book by that title written by Mike McGrath. (I was
expecting it be by Schildt, but even Schildt's code isn't usually
*quite* this bad.)
Amaxon has one review of the book, giving it 5 stars and describing it
as "a quick and easy to understand book for learning C++". I wouldn't
trust a reviewer who doesn't even notice what language a book covers.
accu.org has two reviews of the book, one by Pete Goodliffe at
<http://www.accu.org/cgi-bin/accu/rvout.cgi?from=0au_m&file=c003350a>
and one by Francis Glassborow at
<http://www.accu.org/bookreviews/public/reviews/c/c003566.htm>.
Though I haven't seen the book, I strongly suspect the latter review
is more accurate.
> #include<stdio.h>
>
> typedef struct
> {
> union{ int num; char letter; };
> char *name;
> } info;
>
> int main(void)
> {
> info stored; /* create a struct of the info type */
> printf("Please enter your first name: ");
> gets(stored.name);
> printf("Enter a number to convert to hex? [Y or N]: ");
> scanf("%c",&stored.letter);
> if(stored.letter == 'y' || stored.letter == 'Y')
> {
> printf("OK, enter the number to be converted; ");
> scanf("%d",&stored.num);
> printf("Thanks %s, ",stored.name);
> printf("%d in hex is 0x%X\n", stored.num, stored.num);
> }
> return 0;
> }
Is this *really* what's printed in the book? That's just horrible.
It might be a good exercise for a more advanced book, but only if the
point is to find all the errors.
This book is teaching you bad habits that could haunt you for years,
until you unlearn them. Get rid of the book. Don't give it to
someone else who might actually use it. If you give it away, tape a
copy of Francis Glassborow's review inside the front cover.
K&R2 (_The C Programming Language_, 2nd Edition, by Kernighan &
Ritchie) is generally considered the very best C tutorial, but it's
aimed at readers who already have some programming experience. If you
need something more elementary, I'm sure someone here can recommend
something good.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.