Printing leading zeros in a number in C

19.1k Views Asked by At

I'm working on a project and I want my program to read a strictly 5 digits number with a leading zero.

How can I print the number with the leading zero included?
Plus: how can I provide that my program reads 5 digits including a zero as a leading number?

3

There are 3 best solutions below

1
Stephan Lechner On BEST ANSWER

The best way to have input under control is to read in a string and then parse/analyze the string as desired. If, for example, "exactly five digits" means: "exactly 5 digits (not less, not more), no other leading characters other than '0', and no negative numbers", then you could use function strtol, which tells you where number parsing has ended. Therefrom, you can derive how many digits the input actually has:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int main() {

    char line[50];
    if (fgets(line,50,stdin)) {
        if (isdigit((unsigned char)line[0])) {
            char* endptr = line;
            long number = strtol(line, &endptr, 10);
            int nrOfDigitsRead = (int)(endptr - line);
            if (nrOfDigitsRead != 5) {
                printf ("invalid number of digits, i.e. %d digits (but should be 5).\n", nrOfDigitsRead);
            } else {
                printf("number: %05lu\n", number);
            }
        }
        else {
            printf ("input does not start with a digit.\n");
        }
    }
}
1
kiran Biradar On

I assume you want to read in int variable. If so you can try the below solution.

#include<stdio.h>
void main()
{
  int a;

  scanf("%5d", &a);
  printf("%05d",a);

}
0
Eliyahu Machluf On

use printf family with '%05d" to print number with leading zeros. use sscanf to read this value (leading zeros are ignored).

Consult the following code:

int a = 25;
int b;
char buffer[6];
sprintf( buffer, "%05d", a );
printf( "buffer is <%s>\n", buffer );
sscanf( buffer, "%d", &b );
printf( "b is %d\n", b );

output is:

buffer is <00025>

b is 25