sprintf format for date::year_month_day

I'm getting this warning on my program :

```
OC/HelpOC.cpp:711:43: warning: format '%d' expects argument of type 'int', but argument 3 has type 'date::year_month_day' [-Wformat=]
sprintf(buffer, "%010d", task->startdate);
```

I've looked and have not been able to find a way to be rid of it. The code works fine.
What format can I use instead to make this go away?
What is actually put into buffer after the call?
Can you point us to documentation for the date::year_month_day object type?

Without knowing more, my guess is that it's undefined behavior and just happens to work. My guess is that your buffer just contains garbage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Example program
#include <cstdio>
#include <cstdint>

// Don't copy this part... just to make code compile
namespace date {
struct year_month_day
{
    std::int16_t year;
    std::uint8_t month;
    std::uint8_t day;
};
} // namespace date

int main()
{
    struct Task {
        date::year_month_day startdate;   
    };   
    Task task_obj;
    Task* task = &task_obj;  
    task->startdate.year = 1992;
    task->startdate.month = 3;
    task->startdate.day = 25;

    // Your code: //
    //
    char buffer[100] = {};
    sprintf(buffer, "%04d%02d%02d",
        task->startdate.year, task->startdate.month, task->startdate.day);
    //
    ////////////////
    
    printf("%s", buffer);
}

19920325

Last edited on
Sounds like boost Date_Time: https://www.boost.org/doc/libs/1_72_0/doc/html/date_time.html
It could be C++20, but the date:: is indicative of the boost version.
You can tell the compiler to stop complaining by casting that value to an int, as in:
 
sprintf(buffer, "%010d", static_cast<int>(task->startdate));


Obviously, you're playing with fire if you don't know what a date::year_month_day actually is.

Also, no one should be using sprintf, a sensible alternative is snprintf, which takes the size of the buffer as an argument.
Registered users can post here. Sign in or register to post.