ftp.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/11/30/20:17:37

From: "Weiqi Gao" <weiqigao AT crl DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: scanf()
Date: 1 Dec 1996 00:06:44 GMT
Organization: CRL Dialup Internet Access
Lines: 46
Message-ID: <01bbdf1b$520b3d80$010200c0@weiqigao>
References: <32A0A0CE DOT 622C AT exis DOT net>
NNTP-Posting-Host: crl10.crl.com
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019