ftp.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/11/30/22:43:33

Date: Sat, 30 Nov 1996 22:22:52 -0500 (EST)
From: Michael Phelps <morphine AT hops DOT cs DOT jhu DOT edu>
To: Joe Wright <wrightj AT exis DOT net>
cc: djgpp AT delorie DOT com
Subject: Re: scanf()
In-Reply-To: <32A0A0CE.622C@exis.net>
Message-ID: <Pine.GSO.3.95.961130221439.18751A-100000@hops.cs.jhu.edu>
MIME-Version: 1.0

On Sat, 30 Nov 1996, Joe Wright wrote:

> 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);

There's your problem:  try scanf("%lf", &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()?  
No.  All scanf() knows is that you're giving it a pointer.  You need to
explicity let it know if it should be a float or double.
> 
> I'm getting really tired of scanf().  
> 
> Joe
> 
Actually, the most bullet-proof method for reading numbers is to use
fgets() and sscanf(), rather than scanf().  For example:
	
char	buffer[100];
double	number;
...
printf("Enter number:  ");
fgets(buffer, 100, stdin);
if (sscanf(buffer, "%lf", &number) != 1)
	printf("Incorrect format.\n");
/* else number is okay */

						--Michael Phelps


- Raw text -


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