Intaek LIM <li******@nownuri.net> wrote:
Hello.
I always used cin in C++ for standard input.
But, with C, I must use scanf.
Integers, chars are all fine with scanf.
The problem is... I cannot read floating point value like 'double' with scanf.
-----------------------
double d;
printf("Input a value : ");
scanf("%f", &d); // it does not works!
printf("%f", d); // result is 0.000000 in Dev-Cpp, garbage value in VC++
-----------------------
But when I changed %f with %lf, it worked!.
I do not know why. Please let me know.
(The fact throw me into confusion is, being with '%f' works with printf.)
ps. My english is not perfect because it is not my mother tongue. :-)
In fact many seem to imply that format specifiers of the printf family
and the scanf family of functions do the same, but how could they? While
printf is supposed to produce formatted output scanf is supposed to read
formatted input. It should be clear that the two require different
arguments.
Wherever possible, format specifiers seem to have been choosen to be as
similar as possible in both scanf and printf, but they usually require
different arguments.
As to what the problem with double/float is with format specifiers,
float is just plain simply passed as double when it is passed through a
not prototyped function or part of function. That is with printf being a
so called variadic function, even if you where passing a float value to
printf it would get passed as double and printf would have to access it
as double. So there is no need for printf to distinguish the two.
But scanf, doesn't get a float or double, it gets pointer to float or
pointer to double, which are not magically converted to something other,
so this requires that scanf needs to know which is being passed and this
is achieved by using the l-modifier for the %f format specifier when
passing double.
BTW, saying "I don't know why" is like saying "I'm to lazy to look it
up". You probably meant "I don't understand why, even though I read the
documentation (or FAQ, or else)".
--
Z (Zo**********@daimlerchrysler.com)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond