Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a const char* from a custom printf function

I've written a custom print function. My problem is that I need to return a const char* as this has to be used in another function. I simply have no idea how to manage that...

anotherFunction (const char* text /*Here*/, unsigned __int32 value, unsigned __int64 bigVal);

I know the following example/s do/es not work as it should. That's what I've tried so far.

const char* CatchMessage (const char *message, ...)
{
    va_list  args;
    va_start (args, message);
    /*?*/
    va_end   (args);
    return message;
}

I've yet only managed to get the correct output in cmd, but I actually need it as return value.

void CatchMessage (const char *message, ...)
{
    va_list  args;
    va_start (args, message);
    vfprintf (stdout, message, args);
    va_end   (args);
}

Call:

CatchMessage ("Some Input %s and %d equals to %d", randString, randNumber, secRandNumber);

Should return:

"Some Input stuff and 12 equals to 6"

I have not been able to find a solution. Any help would be appreciated.

Q: How do I get this CatchMessage function to return the correctly formatted const char* ?

like image 261
Blacktempel Avatar asked Nov 13 '13 09:11

Blacktempel


2 Answers

It sounds like CatchMessage should take a pointer to a char buffer (and its size), and vsnprintf() into that buffer.

like image 190
NPE Avatar answered Oct 01 '22 18:10

NPE


Since you're using C++ (at least according to the tags on the question) why not just return the string in a std::string ?

like image 23
Sean Avatar answered Oct 01 '22 18:10

Sean