Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable number of arguments to printf/sprintf

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.

like image 208
user5722 Avatar asked Jun 29 '09 03:06

user5722


People also ask

How can printf () and scanf () take multiple arguments?

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.

How many arguments can be passed to printf?

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 ;) )

How many arguments can be passed to scanf?

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.

What is Variadic function in C?

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.


2 Answers

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.

like image 98
John Kugelman Avatar answered Oct 12 '22 19:10

John Kugelman


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);
}
like image 24
Lodle Avatar answered Oct 12 '22 17:10

Lodle