mike jackson
mike jackson

Reputation: 29

c integer starts with 0

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

Answers (4)

August Karlstrom
August Karlstrom

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

Eric Postpischil
Eric Postpischil

Reputation: 222828

  1. If the user enters “05” and you read it using 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.
  2. If you use ”0” as the first digit of a constant in C source code, it introduces an octal constant, so that 010 represents eight.
  3. If you want to print a leading “0” before a number, you can simply include it literally in the format string: printf("0%d", x);.
  4. If you want to print the string with at least a certain number of digits, with as many leading zeros as necessary to give that many digits, you can use “0n” in the format specification, where “n” is the number of digits: printf("%02d", x);.
  5. If you want to combine the above and print a zero in front of the number if and only if the user entered a zero in front of the number, you need to write source code that adjusts what is printed based on what was seen in input. (The easiest way to do this may be to record the characters the user types and just print those exactly.)

Upvotes: 0

John Bode
John Bode

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

J.Antoniou
J.Antoniou

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

Related Questions