Phoenix
Phoenix

Reputation: 420

How to pass a formatted string as a single argument in C?

How would I go about formatting a string and passing it as a single argument in C? If I wanted to use sprintf(), I would have to create a variable first and then store the formatted result in there before passing the variable. This feels messy. Is there any way around this? Or is that how it should be done?

Upvotes: 1

Views: 3729

Answers (1)

dxiv
dxiv

Reputation: 17648

The "messy" part can be isolated into a helper myFmtFunction function, which builds the string then calls the real myFunction. The formatting helper could actually be reused for different myFunction targets, by passing an additional function pointer argument (though the sample code below does not do that, in order to keep it simpler).

#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>

void myFunction(const char *msg)
{ printf("[myFunction] %s: %d\n", msg, rand() % 6 + 1); }

void myFmtFunction(const char *fmt, ...)
{
  // determine required buffer size 
  va_list args;
  va_start(args, fmt);
  int len = vsnprintf(NULL, 0, fmt, args);
  va_end(args);
  if(len < 0) return;

  // format message
  char msg[len + 1]; // or use heap allocation if implementation doesn't support VLAs
  va_start(args, fmt);
  vsnprintf(msg, len + 1, fmt, args);
  va_end(args);

  // call myFunction
  myFunction(msg);
}

int main() {
  const char s[] = "dice roll";
  const int n = 3;
  for(int i = 1; i <= n; i++)
    myFmtFunction("%s %d of %d", s, i, n);
  return 0;
}

Possible output:

[myFunction] dice roll 1 of 3: 2
[myFunction] dice roll 2 of 3: 5
[myFunction] dice roll 3 of 3: 4

Upvotes: 3

Related Questions