• Advertisement

Archived

This topic is now archived and is closed to further replies.

Variable arguments: creating an sprintf wrapper?

This topic is 5500 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''ve got a class that maintains an error log. Currently, if I want to record the value of some variable, I have to first declare an array to store a string, then use sprintf() to load that string with the data I want, then pass the string to my error-recording function. That''s not cool. Instead, it would be a lot better if my error-recording function worked similarilly to the sprintf() line of functions. However, I''m having a lot of trouble getting this to work. At the core of it, all I''m trying to do here is to create a wrapper function for sprintf. I''m including stdarg.h, and I''ve declared my function with the function(char * s, ...); syntax. However, I can''t figure out how to define that function so that it calls sprintf with the information it has been given. Is there any easy way to do this? Or am I going to have to write a function that performs the same string-parsing work as sprintf does?

Share this post


Link to post
Share on other sites
Advertisement
look into va_list, va_start and va_end
here''s some working code i use:


  
void tConsole::Print ( const char *msg, ... )
{
va_list argList;
char buffer[512] = { 0 };
va_start(argList, msg);
vsprintf(buffer, msg, argList);
va_end(argList);

// now buffer contains the formatted message..

// do with it whatever you want :)


}



Runicsoft -- latest attraction: obfuscated Brainfuck Interpreter in SML
( This post was made entirely from re-cycled electrons )

Share this post


Link to post
Share on other sites
Unless you are coding in C, I suggest you learn how to use C++ stringstreams instead.

The 512 char buffer is the main reason behind buffer overflows security exploits so commonly found these days.

Share this post


Link to post
Share on other sites
quote:
Original post by Zorodius
I''ve got a class that maintains an error log.
[...]
all I''m trying to do here is to create a wrapper function for sprintf. I''m including stdarg.h, and I''ve declared my function with the function(char * s, ...); syntax.

I''m reminded of this thread.

Share this post


Link to post
Share on other sites

  • Advertisement