0

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?

4
  • I assume you have verified that 'timeStepNumber == 1' by displaying the value prior to calling 'string_print()' ? Commented May 10, 2014 at 7:11
  • @MahonriMoriancumer Yes - prior to calling string_print, and also inside (before an actual calling snprintf) Commented May 10, 2014 at 7:14
  • why have you elected to use 'snprintf()' instead of using 'int vsnprintf(char *str, size_t size, const char *format, va_list ap);' ? Commented May 10, 2014 at 7:18
  • because of "copy-paste" =) snprintf was used originally in code - looks like it's an error I'm looking for. Commented May 10, 2014 at 7:23

2 Answers 2

1

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

vsnprintf(str, size, format, args);

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.