ipkiss
ipkiss

Reputation: 13661

Question about scanf() with lf specifier and printf() with lf specifier?

I am learning C and I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char *argv[])
{
  double x;
  printf("x = ");
  scanf("%ld", &x);
  printf("x = %lf\n", x);

  system("PAUSE");  
  return 0;
}

(I am using Dev C4.9, Windows XP SP3)

When I run the above program and entered 5.3; the program printed x = 0.000000

Can anyone explain why is that, please?

Thanks a lot.

Upvotes: 1

Views: 1045

Answers (4)

Steve Wellens
Steve Wellens

Reputation: 20640

It's better to use gets() and then try to parse and convert the entered string to the desired type.

Because everything is input initially as a string and it's easier to handle bad input.

scanf requires the input to be perfect and that doesn't always happen when humans are keying in data.

Upvotes: -1

Gareve
Gareve

Reputation: 3391

Be consistent with the data with scanf and printf. Plus for %lf(double), %f(float), %lld(long long int) i've experienced problem in windows. It's not well implemented in windows (msvcrt.dll if you ask).

Upvotes: 0

edgarmtze
edgarmtze

Reputation: 25058

for your scanf ld:

same as "%d" except argument is "long" integer. Since "long"
is the same as "int" on GCOS8,this is the same as "%d". However, the compiler 
will warn you if you specify "%ld" but pass a normal "int", or specify "%d" but 
pass a "long".

for your printf lf:

same as "%f" except argument is "long double". 
Since "long double" is the same as "double" on GCOS8, this is the same as "%f". 

read this.

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400622

The %ld format string means that it's expecting to read in a long signed int, but you're passing it instead a double. You should instead use the %lf format specifier to say that you want a double.

Note that for scanf, the l is required for doubles (and is required to be absent for floats), whereas for printf, the l in %lf has no effect: both %f and %lf have the same output for both floats and doubles, due to default argument promotion.

Upvotes: 4

Related Questions