Search code examples
cinputintegerscanfzero

Why I am unable to take integer input starting with zero?


I am trying to take integer input in c using the scanf function.

When I give the input as 5 it prints 5 but when the input is 05 it is omitting the 0 and prints 5.

Can someone please help me, I don't understand what is wrong.

int main(){
    int n;
    scanf("%d",&n);
    printf("%d",n);    
}

My input was 05

Excepted output is 05
Actual output is 5


Solution

    1. 5 as int type is same is 05 as int.
    2. If you want to print digits in format "05" or "020" i.e. with a leading zero, use

      printf("%02d",var);// for 1 digit variable with one leading zero

      printf("%03d",var);// for 2 digit variable with one leading zero,for 1 digit variable with two leading zero

      printf("%04d",var);// for 2 digit variable with two leading zeros,for 1 digit variable with three leading zeros

      and so on. Increment value before d if you want more leading zeros.