passing a variable no. of arguments into sprintf (...)

S

Simon L

Morning all,

I'm converting my windows exe into a windows service and to get some
log information I'm replacing TRACE with my own Log.

Since some of the Trace statements take a number of arguments I want to
be able to stuff any number of arguments into my log, as in sprintf.

eg Log( "%s %i Hello", "Hi", 23) gives me 122334 !£., Hello with the
following code.

void CLog::Log(LPCTSTR lpszData ...)
{
va_list ap;
va_start(ap, lpszData);
char cRtn[256];
sprintf(cRtn, lpszData, ap); //doesn't work
va_end(ap);

//do something useful with cRtn

}

Any suggestions? I'm guessing that 122334 is a pointer...
 
H

Heinz Ozwirk

Simon L said:
Morning all,

I'm converting my windows exe into a windows service and to get some
log information I'm replacing TRACE with my own Log.

Since some of the Trace statements take a number of arguments I want to
be able to stuff any number of arguments into my log, as in sprintf.

eg Log( "%s %i Hello", "Hi", 23) gives me 122334 !£., Hello with the
following code.

void CLog::Log(LPCTSTR lpszData ...)
{
va_list ap;
va_start(ap, lpszData);
char cRtn[256];
sprintf(cRtn, lpszData, ap); //doesn't work
va_end(ap);

//do something useful with cRtn

}

Any suggestions? I'm guessing that 122334 is a pointer...

Use vsprintf...

Heinz
 
P

Peter Steiner

have you looked into the usage of boost::format over a printf like
approach? it's format strings are compatible to printf (which eases
transition), provide additional functionality and are fully type
checked, and all that for a minor performance cost.

imho the ellipsis should be avoided where possible as finding bugs in
it's usage is very difficult.

you would use

Log(boost::format("%s %i Hello") % "Hi" % 23)

instead of

Log( "%s %i Hello", "Hi", 23)

TRACE calls should be replacable automatically with a proper regex in
your existing code.

http://boost.org/libs/format/

-- peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top