I have a class that holds an "error" function that will format some text. I want to accept a variable number of arguments and then format them using printf.
Example:
class MyClass
{
public:
void Error(const char* format, ...);
};
The Error method should take in the parameters, call printf/sprintf to format it and then do something with it. I don't want to write all the formatting myself so it makes sense to try and figure out how to use the existing formatting.
Each argument takes a size of integer in stack. For data types whose sizes are greater than integer, double or multiples of integer size are taken. Inside the function, we take the pointer of the first argument. We can get the next argument by incrementing the pointer value.
Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) )
In this case, scanf() has always exactly two arguments. The way to determine how many arguments a function is receiving is to look at your code and search with your eyeballs for the function call in question. Also, your comparison of an array of char s to a single char makes absolutely no sense.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
void Error(const char* format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); }
If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf
instead of vsprintf
. vsnprintf
will prevent an accidental buffer overflow error.
have a look at vsnprintf as this will do what ya want http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/
you will have to init the va_list arg array first, then call it.
Example from that link: /* vsprintf example */
#include <stdio.h>
#include <stdarg.h>
void Error (char * format, ...)
{
char buffer[256];
va_list args;
va_start (args, format);
vsnprintf (buffer, 255, format, args);
//do something with the error
va_end (args);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With