如何实现类似于sprintf那样接受变参的函数?

shi_hang_nk 2010-07-15 05:57:41
我想写一个函数,接收类似于printf()函数那样的变参,进行一些处理后,再调用sprintf()去生成一个字符串。

我觉得难点在于如何把接收到的参数再传给sprintf,没想出什么好办法。
...全文
263 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
codelabs 2010-07-16
  • 打赏
  • 举报
回复
变参函数。。。
small_bull 2010-07-15
  • 打赏
  • 举报
回复
学习一下可变参数函数实现原理就会明白怎么用了。
G_Spider 2010-07-15
  • 打赏
  • 举报
回复
给你个例子吧,以前也没用过,刚写的。


#include<stdio.h>

int add(int x,int y)
{
return x+y;
}

void myfun(int (*func)(int,int),int a )
{
int b;
b=func(2,3);
printf("\n%d %d",a,b);
}
void main()
{

myfun(&add,4);

}
风子II 2010-07-15
  • 打赏
  • 举报
回复
不定参数函数
int MyPrintf(char* pcszFormat, ...)
{
va_list pArgList;
va_start(pArgList, pcszFormat);
char* szBuffer = new char[MAX_PATH];
_vstprintf_s(szBuffer, MAX_PATH, pcszFormat, pArgList ); //将参数列表的内容存放在szBuffer 里
va_end(pArgList);
delete []szBuffer;
return 0;
}

使用可变参数宏
#ifdef NDEBUG
#define DEBUG_PRINT(format,...)
#else
#define DEBUG_PRINT(format,...) printf(format,__VA_ARGS__)
#endif

注意,__VA_ARGS__前后都是两个下杠
mstlq 2010-07-15
  • 打赏
  • 举报
回复
http://dev.firnow.com/course/3_program/c++/cppjs/20090307/158831.html
silenceburn 2010-07-15
  • 打赏
  • 举报
回复
没看太明白,如果是你说的难点,你应该只要重点关注如何根据变量类型,组装拼出合适的格式化描述串即可

如果是指写可变参函数 ,stdarg.h 里有你想要的东西

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧