Reputation: 1744
Note:This question is very simple but when I am searching in Google I haven't got any clear clarification.
I have following program
int main()
{
float c;
scanf("%f",&c);
printf("%f",c);
}
o/p
when I am giving a int
value (e,g - 9) it is showing it as 9.000000
but when I am giving char value like 'a' it is not showing and showing 0.000000.I know the memory representation of float
is totally different from int
but then how when I am giving int value (9)
it is showing but when I am giving char (a)
which is also an int (97) is not showing.
How it is happening. What is the memory representation during char
assignment.
Upvotes: 3
Views: 1277
Reputation: 137468
Note that there are no char
s here anywhere in your code.
This is the way scanf
is supposed to work. If you check the return value from scanf
(like you should be!) you'll probably see that it's returning 0, meaning no items were matched.
When you give scanf()
a "%f"
format string, that means "I want you to try and get me a floating point number. When you provide input like 'a', it's not going to match anything, because 'a'
is not a valid floating-point number.
http://www.cplusplus.com/reference/cstdio/scanf/
Upvotes: 10
Reputation: 1
First, you usually should end your printf
format string with a newline \n
or else call fflush
.
Then, you should read the documentation on scanf
i.e. its man page scanf(3)
It can fail, and it returns the number of successful matches:
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
A failure is happening when you type an input letter a
against a %f
conversion specification. In your case the c
variable is left unchanged (i.e. "uninitialized").
You should test the result of scanf
(it is <=0
on failure in your case).
Upvotes: 4
Reputation: 1570
scanf
in the form you wrote it will try to find and read numbers (int
/float
) up to the first non numerical character (newline, space, any letter). Letters are int
s, but this is because of the scanf
and the way it should behave. Read up the docs.
Upvotes: 1