Reputation: 89
Hi I am now learning the C language and I have a little problem with a exercise of the book I read. My code is this:
#include<stdio.h>
int main()
{
unsigned char one=0;
unsigned char two=0;
printf("Quantity 1 = ");
scanf("%d",&one);
printf("Quantity 2 = ");
scanf("%d",&two);
printf("The value is %d",one);
return 0;
}
Why when I am trying to see the value of one
the initial value appears and not the value after the scanf
?
Upvotes: 5
Views: 9525
Reputation: 22157
You need to use int
type in conjuction with %d
specifier, and char
with %c
specifier. And %u
with unsigned integers.
#include<stdio.h>
int main()
{
unsigned int one=0; unsigned int two=0;
printf("Quantity 1 = ");scanf("%u",&one);
printf("Quantity 2 = ");scanf("%u",&two);
printf("The value is %u",one);
return 0;
}
Basicaly, scanf
will try to read integer from input and it will try to store it inside memory location that is not large enough, so you will have undefined behavior.
You can find good reference here.
However, if you try to use character for an input type, you may want ask yourself why you won't get a chance to enter a second Quantity (if you type 4
and press enter). This is because second scanf
will read enter key as a character. Also, if you try to type 21
(for a twentyone), it will fill the first value with 2
and second with 1
(well, with their ASCII values).
So, be careful - be sure that you always choose the right type for your variables.
Upvotes: 8
Reputation: 64682
You declared the variable one
to be a char:
unsigned char one=0;
But then you told scanf
to read an int
:
scanf("%d",&one); /* %d means int */
Int is bigger than char (typically 4-bytes vs. 1-byte), causing the problem you describe.
Change your scanf
to:
scanf("%c",&one); /* %c means char */
Then when you print out the value, also print a char:
printf("The value is %c",one); /* %c means char */
Upvotes: 1
Reputation: 140619
Never use scanf
.
Never use scanf
.
Seriously, never use scanf
.
Use fgets
(or getline
, if you have it) to read an entire line of input from the user, then convert strings to numbers with strtol
or its relatives strtod
and strtoul
. strsep
may also be useful.
Upvotes: 2
Reputation: 106012
Change
unsigned char one=0; unsigned char two=0;
to
unsigned int one=0; unsigned int two=0;
and also use %u
instead of %d
then it will print the value after scanf()
.
Upvotes: 1