Tahlil
Tahlil

Reputation: 2731

Debug assertion failure while using strftime

My code is below,

time_t t;
struct tm tm;
struct tm * tmp;
time( &t ); 
tmp = gmtime(&t);

char buf[100];
strftime(buf, 42, "%F", tmp); // assertion failure

It says `expression:("Invalid format directive",0). I wanted to convert the time to Short YYYY-MM-DD date, equivalent to %Y-%m-%d format.

Same thing happens when I try this,

const char* fmt = "%a, %d %b %y %T %z";

if (strftime(buf, sizeof(buf), fmt, tmp) == 0) // assertion failure
{ 
    fprintf(stderr, "strftime returned 0");
    exit(EXIT_FAILURE); 
} 

Upvotes: 0

Views: 2051

Answers (2)

Dave
Dave

Reputation: 46339

%F, %T and %z were introduced by C99, and only came to C++ in C++11. From the comments on your question, it appears you're using Microsoft's partial implementation of C++11 in VisualStudio 2010. Unfortunately your only options are:

  • update your IDE (I don't know if later versions support this, but I'd imagine they do)
  • switch to a different IDE (anything which uses GCC for its compiler will certainly support this)
  • avoid using the newer formatting flags (you can find a list here: http://www.cplusplus.com/reference/ctime/strftime/ anything yellow is new)

Upvotes: 1

daouzli
daouzli

Reputation: 15328

The following worked for me:

#include <stdio.h>
#include <time.h>

int main(int argc, char **argv)
{
    time_t t;
    struct tm tm;
    struct tm * tmp;
    time( &t ); 
    tmp = gmtime(&t);

    const char* fmt = "%a, %d %b %y %T %z";
    char buf[100];
    if (strftime(buf, sizeof(buf), fmt, tmp) == 0) // assertion failure
    { 
        fprintf(stderr, "strftime returned 0");
        return 1; 
    }
    printf("%s\n", buf);

    return 0;
}    

The output is:

Fri, 23 May 14 06:48:27 +0000

Upvotes: 0

Related Questions