Mail Archives: djgpp/1996/11/30/20:17:37
Joe Wright <wrightj AT exis DOT net> wrote in article <32A0A0CE DOT 622C AT exis DOT net>...
> I think this is a djgpp question rather than a comp.lang.c one.
> Maybe not, but.. I have only one C compiler and its DJ's 2.0.
>
> The stdio scanf() is giving me a fit. First, if I only press
> <Enter> when it is waiting for input, it hangs the system. Only
> ^C gets me out with a SIGINT to the DOS prompt. Is that 'defined'
> behavior? This next one drove me crazy for an hour..
>
> double d = 6998.82;
> .....
> printf("Amount = ");
> scanf("%f", &d);
>
> I type what I like, scan() executes but d doesn't change. After
> pulling some already sparse hair looking for bugs, I try compiling
> it with -Wall and guess what. gcc says "%f" is float and d is
> double. I know that! When I declare 'float d;', scanf() does as
> expected. Now I know that "%f" in a printf() string is promoted
> to double. Is this not the case for scanf()?
>
> I'm getting really tired of scanf().
>
Have you read the FAQ list yet?
To answer your question:
1. scanf() is determined to get a number out of the stdin, pressing <Enter>
cannot make it go away. It is still waiting for a number.
2. The format string for printf() and scanf(), though similar, are not
interchangable. Read the info page very carefully to learn what they do.
3. The value of d was indeed changed by the scanf() statement. Here is
how it worked: When you declared "double d", eight bytes of memory are set
aside to hold the value. When you told scanf() that you wanted a "%f",
scanf() happily went to stdin and got you a four byte float value (that's
what "%f" is, a four byte floating point number). When you told scanf()
that you want the number to be stored in &d, scanf() obliged, and indeed
put the four byte float into the address &d. This changed the first four
bytes of the double value of d. Since DOS is little endian, the first four
bytes are the least significant part of d, that's why the value of d
seemed unchanged.
4. To get a eight byte double number from stdin, you need to specify "%lf".
5. Bugs rarely reside in sparse hair.
--
Weiqi Gao
weiqigao AT crl DOT com
- Raw text -