我过去几年一直在使用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标准库中是否有可用的函数可以帮助我,或者,有没有一种方法可以使用数组调用可变参数函数?)
请注意,参数数量永远不会超过我的数组长度。并且类型始终为字符串。所以,我可能会有:
char *formatString = "My Formatted String %s.%s.%s";
char *formatValues[] = {"a","b","c","d","e"};
但我永远不会少 %s。
注意:C 代码必须适用于 Linux 的 GCC 和 Windows 的 Visual Studio(C90)。
sprintf()
然后再使用strcat()
。另外,请使用snprintf()
代替sprintf()
,这样可以在一定程度上减少缓冲区溢出错误的可能性。 - user529758