Question

I want to have something like a cross platform snprintf function, so I'm trying to use this (perhaps there are other solutions, but I'm wondering exactly that):

void string_print(char *str, size_t size, const char *format, ...) {
    va_list args;
    va_start(args, format);
#ifdef _WIN32
    sprintf_s(str, size, format, args);
#else
    snprintf(str, size, format, args);
#endif
    va_end(args);
}

Example of usage:

// timeStepNumber == 1
char fileName[40];  
string_print(fileName, 40, "Flow%d.dat", timeStepNumber);

But in this case I have fileName == "Flow-14843.dat", although va_arg(args, int) == 1. Can anybody explain, what maybe wrong in the string_print function?

Was it helpful?

Solution

You need to use vsnprintf/vsnprintf_s functions with vararg lists.

vsnprintf(str, size, format, args);

OTHER TIPS

As indicated by imbtfab, use vsnprintf() in place of snprintf() and _vsnprintf() in place of sprintf_s.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top