Printing leading zeros in a number in C
Solution 1
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");
}
}
}
Solution 2
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);
}
Solution 3
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
Related videos on Youtube
zx485
Updated on June 04, 2022Comments
-
zx485 almost 2 years
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?-
Norhther over 5 yearsShow us some code
-
Greg K. over 5 yearsHow do you want to input numbers in your program? Console or through a file? Give us a context for your program.
-
Martin James over 5 yearsWhat type is the number? Integer? Can you not just read is as a string and verify/numberify it after?
-
Weather Vane over 5 yearsYou have asked three questions (the first implied). Please don't ask several as if you are in a tutorial. If you use the format specifier
%d
inscanf
then leading zeros are ignored. If you use the format specifier%i
then a leading zero indicates an octal value. -
Weather Vane over 5 yearsIf you want exactly 5 digits entered then use a string type input. The question is also unclear about "with a leading zero", must there always be a leading zero? Please post example inputs and required output.
-
-
Jonathan Leffler over 5 yearsThis will accept from 1 to 5 digits (plus a sign) on input. Assuming the number isn't negative, it will print the value with leading zeros.
-
Admin over 5 yearsOn point . Thank you very much.