先上一段代码:

#include<cstdarg>
#include<iostream>
#include<string>
using namespace std;
void error(char* format,...){//至少要有一个参数,后边的...表示参数可变
va_list ap;
int d,flag;
char c, *s;
va_start(ap,*format);//从args参数开始后面都是可变参数,va_start,va_end都为宏
while (*format){
switch (*format) {
case 's': /* string */
if(!flag) break;
s = va_arg(ap, char *);
cout<<s;flag=;
break;
case 'd': /* int */
if(!flag) break;
d = va_arg(ap, int);
cout<<d;flag=;
break;
case 'c': /* char */
/* need a cast here since va_arg only
takes fully promoted types */
if(!flag) break;
c = (char) va_arg(ap, int);
cout<<c;flag=;
break;
case '%':
flag=;
break;
default:
putchar(*format);
}
format++; }
putchar('\n');
/*for(i=0;i<args;i++){//遍历所有其他参数
//printf("%d",va_arg(ap,int));
}*/
va_end(ap);//destroy va_list;
}
int main(){
char s[]="rich";
error("I am %s,I have %d %c",s,,'$');
//getchar();
return ;
}
其中error()函数像printf一样打印出格式化字符串。
#include <stdarg.h>
头文件中定义了一下一些宏,注意不是函数
void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);
有趣的是va_arg宏,每次处理后ap指向下一个参数,请看man手册:
va_arg()
The va_arg() macro expands to an expression that has the type and value
of the next argument in the call. The argument ap is the va_list ap
initialized by va_start(). Each call to va_arg() modifies ap so that
the next call returns the next argument. The argument type is a type
name specified so that the type of a pointer to an object that has the
specified type can be obtained simply by adding a * to type. The first use of the va_arg() macro after that of the va_start() macro
returns the argument after last. Successive invocations return the
values of the remaining arguments. If there is no next argument, or if type is not compatible with the
type of the actual next argument (as promoted according to the default
argument promotions), random errors will occur. If ap is passed to a function that uses va_arg(ap,type) then the value
of ap is undefined after the return of that function.

最新文章

  1. Git(最基本使用远程仓库:github)-V1.0
  2. MVC中如何设置路由指定默认页
  3. WordPress搭建Personal Blog 个人博客
  4. JavaScript中的apply和call函数详解
  5. poj2578---三个数中找出第一个大于168的
  6. 一些常用的Intent及intent-filter的信息
  7. Google C++ style guide——命名约定
  8. Entity Framework加载相关实体——延迟加载Lazy Loading、贪婪加载Eager Loading、显示加载Explicit Loading
  9. SAP HANA 中的决策表(Decision Table)
  10. package。。
  11. byte数组和int之间相互转化的方法
  12. 【Alpha发布】网站已经正式发布!
  13. Codeforces Round #117 (Div. 2) D.Common Divisors(KMP最小循环节)
  14. Go Example--锁
  15. #ifdef、#ifndef、#else、#endif执行条件编译
  16. 常用,好用的js代码
  17. C# 多线程并发锁模式-总结
  18. SpringBoot2 启动报错 Failed to auto-configure a DataSource
  19. python gpio
  20. Django的mode的分组查询和聚合查询和F查询和Q查询

热门文章

  1. LeetCode 解题报告索引
  2. windows下安装git &amp; 在git@OSC上推送代码
  3. opencv6.1-imgproc图像处理模块之平滑与形态学操作
  4. .net程序员转行做手游开发经历(二)
  5. HTML5+JS 《五子飞》游戏实现(八)人机对战
  6. 三言两语聊Python模块–单元测试模块unittest
  7. 初用protobuf-csharp-port
  8. 异步dcfifo的读写
  9. 如何解决xml在eclipse下的拼写报错
  10. IE6下margin时,float浮动产生双倍边距