Search code examples
cslash

How to scan a "0" on the months that have one digit?


I am doing this C program where I need to input a date and see whether it is a valid date. However, I do not know how to scan a "0" in front of the days and months that have one digits. Also, the program requires to scan "/" as well. If the user inputs "07-14-1999" it has to be invalid because the user did not input "/". What should I do with these two problems? The following is the code I have so far. Thank you.

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

int main()
{
    int day, month, year;
    printf("Please enter a date to check validity (in the form of MM/DD/YYYY): ");
    scanf("%i%i/%i%i/%i%i",&month, & month, &day, &day, &year, &year, &year &year);


    printf("%i%i/%i%i/%i%i",month, month, day, day, year, year, year, year);


}

Solution

  • You want to scan three integer numbers, so you should use %d once for each number in scanf:

    scanf("%d/%d/%d", &month, &day, &year);
    

    To validate input it makes sense to check number of successfully scanned integers:

    int res = scanf("%2d/%2d/%4d", &month, &day, &year);
    if (res != 3) {
         /* error */
    }
    

    Here %2d means that the max length of that input integer is 2 digits. If everything is scanned correctly you can validate ranges for month, day and year.

    To print leading zero:

    printf("%02d/%02d/%04d", month, day, year);
    

    Here %02d means that the integer is printed by minimum two symbols and zero is prepended if there is only one symbol.


    It is trickier to make sure that the number of input symbols is correct. The above scan pattern also accepts date "1/1/1999". To simplify and to avoid scanning each symbol separately it is possible to read input as a string:

    int day, month, year;
    /* buffer length is enough for 10 date symbols + 1 null terminating
     * character + 1 for too long input */
    char buf[12];
    char dummy_end_test;
    
    printf("Please enter a date to check validity (in the form of MM/DD/YYYY): ");
    
    /* scan as a string with maximum field width 11, check that the number
     * of input characters is exactly 10 */
    if (scanf("%11s", buf) != 1 || strlen(buf) != 10) {
        printf("incorrect input length\n");
        return 1;
    }
    
    /* parse integer numbers from string
     * try to read symbol dummy_end_test to filter input as 11/1/19999 or 11/11/199x
     * if it is possible to read one more character after four digits of year
     * the number of scanned entries is 4 that is invalid input */
    int ret = sscanf(buf, "%2d/%2d/%4d%c", &month, &day, &year, &dummy_end_test);
    
    if (ret != 3) {
        printf("error\n");
        return 1;
    }
    

    Here I used sscanf that scans formatted input from string.

    Anyway it is needed to validate ranges for day, month and year. All those numbers must be greater than 0. Maximum day depends on month and/or on leap year.