您好,欢迎来到[编程问答]网站首页   源码下载   电子书籍   软件下载   专题
当前位置:首页 >> 编程问答 >> C/C++ >> 给函数传递不定参数问题

给函数传递不定参数问题

来源:网络整理     时间:2016/8/28 16:38:13     关键词:

关于网友提出的“ 给函数传递不定参数问题”问题疑问,本网通过在网上对“ 给函数传递不定参数问题”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: 给函数传递不定参数问题
描述:

函数参数函数参数传递

我写了一个函数时向文件写入double类型数组的函数,代码如下:

void WriteText(double *p,double *p1,double *p2)
{
CFile mFile;
mFile.Open(_T("sss.txt"),CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite);
CString ss;
ss.Format("MarkPos:%lf  %lf  %lf  Tart:%lf  %lf  %lf  Word:%lf  %lf  %lf\r\n",p[0],p[1],p[2],p1[0],p1[1],p1[2],p2[0],p2[1],p2[2]);
mFile.SeekToEnd();
mFile.Write(ss,strlen(ss));
mFile.SeekToEnd();
mFile.Close();
}

我现在想做的是,我可以任意传递参数的数量,比如说个数从1-10.
我不想用函数重载的方法,因为那样需要些10个函数
有没有只用一个函数就可以实现的。
就像printf函数里面可以放任意个参数。
求高手们帮忙!
非常感谢!
解决方案1:

参考这个
还有这个

解决方案2:

给你参考


inline void WriteStatLog(unsigned short nLevel,char* pszLogMsg,...)
{
int iListCount = 0;
int nMaxDestLen = 8192;
char szDestBuf[8192] = {0};
va_list pArgList;
va_start(pArgList,pszLogMsg);
iListCount += _vsnprintf(szDestBuf + iListCount,nMaxDestLen - iListCount,pszLogMsg,pArgList);
va_end(pArgList);
if(iListCount > (nMaxDestLen - 1)) 
{
iListCount = nMaxDestLen - 1;
}
*(szDestBuf + iListCount) = '\0';
CSysLog* pSysLog = CreateInstance();
if (NULL != pSysLog)
{
pSysLog->PushLog(T_SYS_STAT,nLevel,szDestBuf,iListCount);
}
}
解决方案3:

采用不定参数,正如你说的如printf。 

解决方案4:

#include 
#include 
void f(int n, ...)
{
  va_list args;
  double *p;
  va_start(args, n);
  while (n-- > 0) {
    p = va_arg(args, double*);
    printf("%lf  ", *p);
  }
  va_end(args);
  printf("\n");
}
int main()
{
  double d1 = 1.234;
  double d2 = 2.345;
  double d3 = 3.456;
  f(1, &d1);
  f(2, &d1, &d2);
  f(3, &d1, &d2, &d3);
  return 0;
}

以上介绍了“ 给函数传递不定参数问题”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3637159.html

相关图片

相关文章