10

I would like to do something like this:

writeLog(printf("This is the error: %s", error));

so i am looking for a function which returns a formatted string.

4
  • 8
    Look up snprintf. Commented Jun 24, 2012 at 19:48
  • 1
    cplusplus.com/reference/clibrary/cstdio/sprintf for sprintf Commented Jun 24, 2012 at 19:50
  • Sorry, but it seems like snprintf does pretty much the same as sprintf, putting the formatted string into a variable. What i am looking for is a function that directly RETURNS the formatted string. Commented Jun 24, 2012 at 19:52
  • 2
    Bear in mind that someone has to release the string that will presumably be allocated by that magical formatting function. Letting writelLog do that is awkward. You might want to consider longer options (or use C++). Commented Jun 24, 2012 at 19:53

2 Answers 2

8

Given no such function exists, consider a slightly different approach: make writeLog printf-like, i.e. take a string and a variable number of arguments. Then, have it format the message internally. This will solve the memory management issue, and won't break existing uses of writeLog.

If you find this possible, you can use something along these lines:

void writeLog(const char* format, ...)
{
    char       msg[100];
    va_list    args;

    va_start(args, format);
    vsnprintf(msg, sizeof(msg), format, args); // do check return value
    va_end(args);

    // write msg to the log
}
Sign up to request clarification or add additional context in comments.

Comments

6

There is no such function in the standard library and there will never be one in the standard library.

If you want one, you can write it yourself. Here's what you need to think about:

  1. Who is going to allocate the storage for the returned string?
  2. Who is going to free the storage for the returned string?
  3. Is it going to be thread-safe or not?
  4. Is there going to be a limit on the maximum length of the returned string or not?

1 Comment

Would a returned string not get freed when the calling method ended and it went out of scope?

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.