Reputation: 29
How can I print the 0 value in front of integer
if user enters 05 printing 05. %d
just ignores the 0
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
x = 05;
printf("%d", x);
return 0;
}
output = 5
Upvotes: 0
Views: 1597
Reputation: 11377
Use the format specifier %02d
:
#include <stdio.h>
int main(void)
{
int x;
x = 05;
printf("%02d\n", x);
return 0;
}
If a user can enter 05 or 5 and you want to distinguish between the two you need to read the input as a string instead. As mentioned by user3121023, note that integers with a leading zero are interpreted as octal numbers, for instance 010
equals 8.
Here is the full documentation of printf: https://pubs.opengroup.org/onlinepubs/9699919799/
Upvotes: 1
Reputation: 222828
scanf
with %d
or something similar, the only result you will get from the scanf
is the value five; there will be no indication whether the user entered “05” or “5”. If you need to know specifically what the user enters, you need to read the input as strings or characters.010
represents eight.printf("0%d", x);
.printf("%02d", x);
.Upvotes: 0
Reputation: 123468
First of all, realize that constants with a leading 0
are interpreted as octal, not decimal. 05
and 5
are the same, but you'll have an issue with something like 09
.
You can specify a minimum output field width like so:
printf( "%2d\n", x ); // minimum field width of 2, pad with blanks
or
printf( "%*d\n", 2, x ); // minimum field width of 2, pad with blanks
To pad with a leading 0, use
printf( "%02d\n", x ); // minimum field width of 2, pad with 0
or
printf( "%0*d\n", 2, x ); // minimum field width of 2, pad with 0.
Upvotes: 1
Reputation: 11
printf("%02d", x);
The zero represents how many digits will the zero padding be so if you wanted to do the same with 10 for example it should be 03 hope this helps.
Upvotes: 0