0
const char* strrep(listing list) {
//https://stackoverflow.com/q/4836534/9295513
char* retVal = //...
return retVal;
}

I have a struct type called listing. Is there a way to format elements as if by calling printf with ("%d %d %s...", list->elem_one, list->elem_two, list->elem_three...) but write the output to an array of char instead of to standard output?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
JohnnyApplesauce
  • 181
  • 1
  • 2
  • 13

2 Answers2

3

The function you want is snprintf. It creates a formatted string and writes it to the given char * argument with a given size instead of to stdout.

For example:

int len = snprintf(NULL, 0, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...);
char *retVal = malloc(len+1);
snprintf(retval, len+1, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...);

The first call is used to figure out how much space is needed. Then you can allocate the proper amount of space and call snprintf again to create the formatted string.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

If I read that right, you're looking to print into a buffer instead of out to the console or a file. If that's the case, you'd want to use sprintf, or it's bounded cousin snprintf. Here's an example from the cplusplus website:

#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

Note that sprintf automatically appends a null terminator, but it's still up to you to make sure the total length of the string can fit into the given buffer.