How do I format a string from an array of values in C?
I've been using C # for the past few years and I'm currently trying to write C. I'm trying to format a string from an array of values. Format string and array are unknown until run time.
In C #, I can call a variable function with an array like:
using System;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string formatString = "{0}.{1}.{2}.{3}";
string[] formatValues = new[] { "a", "b", "c", "d" };
string formatted = String.Format(formatString, formatValues);
//Do something with formatted (now looks like "a.b.c.d")
}
}
}
In C, I have this:
#include <stdio.h>
#include <malloc.h>
int main(int argc, char* argv[])
{
char *formatString = "%s.%s.%s.%s";
char *formatValues[] = {"a","b","c","d"};
char *buffer = (char*)malloc(100 * sizeof(char));
//This doesn't work.....
sprintf(buffer, formatString, formatValues);
//... buffer is junk
return 0;
}
How can I do this in C?
(Is there a nice function in the C standard library that I can use to help me, or perhaps there is a way to call the varargs function with an array?)
Note that the number of arguments will never be greater than the length of the array I have. And the types will always be strings. So I could
char *formatString = "My Formatted String %s.%s.%s";
char *formatValues[] = {"a","b","c","d","e"};
But I will never have too few% s.
Note: C should work on GCC for Linux and Visual Studio for Windows (C90).
source to share
I don't think C provides a standardized way to do this. If you understood the internal implementation <stdarg.h>
on your system, it might be possible to evade a system- specific solution using vprintf (3), but I have another kludge suitable for you ...
Something that will work would involve declaring an array of any size, setting the values you have, and then just passing each element of the array to the calling site, regardless of whether or not they are set.
char *a[5]; // or a[50], whatever you need
// assign the elements you actually have
printf(format_string, a[0], a[1], a[2], a[3], a[4], a[5]);
source to share
The only sprintf accepts array type is a null character array (i.e., a string). This should work:
#include <stdio.h>
#include <malloc.h>
int main(int argc, char* argv[])
{
char *formatStrings[]={"%s","%s","%s","%s"};
char *buffer= (char*)malloc(100 * sizeof(char));
char *formatValues[]={"a","b","c","d"};
char *endofBuffer=buffer;
int valueCount=4;
int i;
for (i=0; i<valueCount; ++i)
{
endofBuffer+=sprintf(endofBuffer, formatStrings[i], formatValues[i]);
if (i<valueCount-1)
endofBuffer+=sprintf(endofBuffer, "%c", '.');
}
printf("%s\n",buffer);
return 0;
}
source to share