C++省略参数(va_list va_start va_arg va_end)的简单应用

时间:2023-02-06 06:20:19

原文参考自:http://www.cnblogs.com/hanyonglu/archive/2011/05/07/2039916.html

 #include <iostream>
#include <stdarg.h>
using namespace std;
#define COUNT 5 const char *data[COUNT] =
{
"hello",
"world",
"java",
"C#",
"Python"
};
void fun(int a,int b,...)
{
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
va_list ap;
va_start(ap,b);
cout<<"defaut="<<va_arg(ap,char*)<<endl;
va_end(ap);
}
void Dolog(const char *szFileName,const char *fmt,...)
{
va_list ap;
va_start(ap,fmt);
FILE *fp = fopen(szFileName,"a+");
if(NULL == fp)
{
return;
}
vfprintf(fp,fmt,ap);
va_end(ap);
fclose(fp);
} int main()
{
int a=,b=;
char str[] = "Hello World";
fun(a,b,str);
for(int i=;i<COUNT;i++)
{
Dolog("log.txt","%s\n",data[i]);
}
system("pause");
return ;
}

log.txt内容:

hello
world
java
C#
Python