在过去的几年中,我一直在使用C#,现在我正在尝试编写一些C。我正在尝试从值数组中格式化字符串。直到运行时才知道“格式字符串”和数组。
在C#中,我可以使用数组调用可变参数函数,如下所示:
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")
}
}
}
在C中,我得到了:
#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;
}
我该如何在C语言中执行此操作?
(C标准库中是否有一个我可以用来帮助我的好函数,或者也许有一种方法可以用数组调用varargs函数?)
请注意,参数的数量永远不会大于我拥有的数组的长度。并且类型将始终是字符串。所以我可能有
char *formatString = "My Formatted String %s.%s.%s";
char *formatValues[] = {"a","b","c","d","e"};
但是我永远不会有太少的%s。
注意:C必须在Linux的GCC和Windows的Visual Studio(C90)上工作。
最佳答案
我不认为C提供了实现此目的的标准化方法。如果您了解系统上<stdarg.h>
的内部实现,则可能有可能混淆涉及vprintf(3)的特定于系统的解决方案,但我为您提供了另一种兼容的冲突...
可行的方法包括声明一个较大的数组,设置您拥有的值,然后仅在调用站点传递该数组的每个元素,而不管它们是否被设置。
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]);