我一直在使用C#的最近几年,现在我正在努力写一些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必须在GCC for Linux和Visual Studio for Windows(C90)上工作。
看看vsprintf中 - http://msdn.microsoft.com/en-us/library/28d5ce15(v=vs.71).aspx – OldProgrammer 2013-02-10 22:51:58
当你编译并会发生什么运行你给的代码?你有任何错误? – 2013-02-10 22:55:33
我不认为你想要什么是可能的一步。你可能想要运行一个循环和'sprintf()'然后''strcat()'。另外,请使用'snprintf()'而不是'sprintf()' - 它有点减少了缓冲区溢出错误的可能性。 – 2013-02-10 22:55:58