To receive a C date range

Asked 2 years ago, Updated 2 years ago, 92 views

Don't you use the scanf function when you're making a calendar program and you want to enter a range? If you enter a range like 2021.05.24-2021.08.09, you want to print out a calendar suitable for the month.

scanf_s("%d.%d.%d-%d.%d.%d,&year,&month,&day,&year,&month,&day)

The program didn't run at all. Is there a separate calendar range?

c scanf

2022-09-20 13:33

1 Answers

If you want to convert the "2021.05.24-2021.08.09" form to date, please refer to the code below

It is more convenient to receive each value through scanf and convert it to strptime after receiving it throughout the string.

Of course, since the type of input contains two dates, it would be better to split it into two based on the letter ' -', right?

#include <stdio.h>
#include <time.h>
void main ()
{
    struct tm t;
    const char* date = (2019-10-21"; // date string: October 21, 2019
    const char* time = "18:16:24"; // time string: 18:16:24 
    char* ret=NULL;
    char buf[256];

    ret = strptime(date, "%Y-%m-%d", &t); // date string to tm structure
    ret = strptime(time, "%H:%M:%S", &t); // time string to tm structure

    strftime(buf, sizeof(buf), "%Y year %m month %d", &t); // tm structure to buf the date
    puts(buf);
    strftime(buf, sizeof(buf), "%H:%M:%S", &t); // time in tm structure to buff
    puts(buf); 
}


2022-09-20 13:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.