Skip to main content
gamedev.net
🔒 Locked

Variable arguments: creating an sprintf wrapper?

Started by Zorodius 4 replies 8k views
Original Post
Zorodius
Zorodius
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?
You don't need to vote for the "lesser of two evils"! Learn about Instant Runoff Voting, the simple cure for a broken democracy!
Burning_Ice
Burning_Ice
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 )
Zorodius
Zorodius
Awesome, vsprintf was exactly what I was looking for. Thanks so much!
You don't need to vote for the "lesser of two evils"! Learn about Instant Runoff Voting, the simple cure for a broken democracy!
Void
Void
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.
SabreMan
SabreMan
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.