Date: Sat, 30 Nov 1996 22:22:52 -0500 (EST) From: Michael Phelps To: Joe Wright cc: djgpp AT delorie DOT com Subject: Re: scanf() In-Reply-To: <32A0A0CE.622C@exis.net> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII 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 > 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