cnumbersdigitleading-zero

Printing leading zeros in a number in C


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?


Solution

  • 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");
            }
        }
    }