Reputation: 77
#include <stdio.h>
int main()
{
int i;
long int l;
long long int ll;
char a;
float F;
double D;
scanf("%i%li%lli%c%f%lf",&i,&l,&ll,&a,&F,&D);
printf("%i\n%li\n%lli\n%c\n%f\n%lf\n",i,l,ll,a,F,D);
return 0;
}
When I tried to print the value of a,F and D in the above program, it is printing 'h' for 'char' and 0.000000 and 0.000000 for float and double every time .
input: 3
444
12345678912345
a
334.23
14049.30493
output:3
444
12345678912345
0.000000
-0.000000
Upvotes: 1
Views: 1377
Reputation: 409296
When you read your input, the character you read is the white-space between 12345678912345
and a
. That means that the next format, the floating point, will try to read the letter a
as a floating pointer value which will not work, and the scanf
function will return without being able to correctly read and parse all input, leading to your output not matching the input. Many standard and system function returns a value saying if it succeeded or failed, the same with the scanf
function, and if it doesn't fail completely it will return the number of successfully scanned and parsed items, which would be less than expected in your case.
The scanf
reference in one of my comments will tell you that most formats skip leading white-space, but "%c"
does not. If you want to skip leading space before attempting to parse a character, you need to tell scanf
to do that, by inserting an actual space in the format string, like this:
scanf("%i%li%lli %c%f%lf",&i,&l,&ll,&a,&F,&D);
// ^
// Notice space here
Upvotes: 0
Reputation: 490328
There's no way to pass a char
or a float
to printf
. They'll be promoted to int
and double
respectively in the processing of being passed.
When you pass a double
, you can use %f
or %lf
(the latter was added in C99 though, so some older compilers don't support it).
If you want your int
printed as a character, you can use the %c
conversion. If you want it printed as a number, you can use the %d
or %i
conversion.
For scanf
you don't want to pass any of the above--you want to pass a pointer to a (char | float | double).
As for the conversion to use, for a pointer to char
you can use either %c
or %s
.
%s
reads a "word"--it skips white-space characters, then reads a group of non-white-space characters.%c
does more like "raw" reading--for example, if you specify %15c
it reads the next 15 characters, regardless of whether they're white-space or not.With both %c
and %s
, you always want to pass a with (like %15s
instead of just %s
) to assure that the user can't enter too much data and overflow the buffer you've provide. scanf("%s", whatever);
is pretty much equivalent to using gets
.
With scanf
, you pass %f
to read a float
and %lf
to read a double
.
Upvotes: 6