是否可以直接通过C省略号调用?

时间:2010-02-01 14:11:19

标签: c++ c

void printLine(const wchar_t* str, ...) 
{
  // have to do something to make it work
  wchar_t buffer[2048];        
  _snwprintf(buffer, 2047, ????);
  // work with buffer
}

printLine(L"%d", 123);

我试过

  va_list vl;
  va_start(vl,str);

这样的事情,但我找不到解决方案。

4 个答案:

答案 0 :(得分:9)

这是一个执行此操作的简单C代码,您必须包含stdarg.h才能使其正常工作。

void panic(const char *fmt, ...){
   char buf[50];

   va_list argptr; /* Set up the variable argument list here */

   va_start(argptr, fmt); /* Start up variable arguments */

   vsprintf(buf, fmt, argptr); /* print the variable arguments to buffer */

   va_end(argptr);  /* Signify end of processing of variable arguments */

   fprintf(stderr, buf); /* print the message to stderr */

   exit(-1);
}

典型的调用是

panic("The file %s was not found\n", file_name); /* assume file_name is "foobar" */
/* Output would be: 

The file foobar was not found

*/

希望这有帮助, 最好的祝福, 汤姆。

答案 1 :(得分:5)

您要使用的是vsprintf它接受va_list参数并且有样本 链接上MSDN上的代码。

编辑: 您应该考虑_vsnprintf,这将有助于避免vsprintf乐意创建的缓冲区溢出问题。

答案 2 :(得分:2)

通常会调用函数的变量args版本,该版本接受va_list。例如_snwprintf内部调用_vsnwprintf;试着调用它。

答案 3 :(得分:2)

其他人已经向您指出了vprintf - 函数系列,但如果您想熟悉其他常见问题条目,comp3.lang.c常见问题还可以(毫不奇怪)回答这个问题。 。 (他们值得一读,IMO。)

How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work?

相关问题