可变参函数
#include <stdio.h>
#include <stdarg.h>
void func(int num, ...)
{
int after = 0;
va_list v; //指针类型
va_start(v, num);
printf("*v = %d\n", *v);
for(int i = 0; i < num - 1; i++)
{
int res = va_arg(v, int); //返回指向下一个va_list类型的指针
//printf("after = %d\t, *v = %d \n", res, *v); //出错
printf("after = %d\n", res);
}
va_end(v);
}
int main()
{
func( 6,1, 2, 3, 4, 5, 6);
}
- 注意:
va_arg
返回值的类型为va_list, 不能直接printf
输出;
void write_log(const char *fmt, ...){
va_list va;
char buf[1024];
va_start(va, fmt);
memset(buf, 0, 1024);
(void) vsprintf(buf, fmt, va);
va_end(va);
printf("%s: %s", "my_log_prehead", buf);
}
int main()
{
write_log("%s\n", "hello world!");
return 0;
}
vsprintf
的用法
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
char buffer[100];
int vspfunc(char *format, ...)
{
va_list aptr;
int ret;
va_start(aptr, format);
ret = vsprintf(buffer, format, aptr);
va_end(aptr);
return (ret);
}
int main()
{
int i = 5;
float f = 27.0;
char str[50] = "hello world!";
vspfunc("%d\n%10.3f\n%s", i, f, str);
printf("%s\n", buffer);
return 0;
}
输出:
5
27.000
hello world!
snprintf
的用法
- 一
#include <stdio.h>
int main ()
{
char buffer [100];
int cx;
cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );
if (cx>=0 && cx<100) // check returned value
snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );
puts (buffer);
return 0;
}
输出:
The half of 60 is 30, and the half of that is 15.
- 二、将可变个参数(…)按照format格式化成字符串,然后将其复制到str中
#include <stdio.h>
#include <string.h>
int main ()
{
char str[6];//最小为6
memset(str, 0, sizeof(str));
snprintf(str, sizeof(str), "%d", 65535);
printf("%s\n", str);
return 0;
}
输出:
65535$
参考:https://blog.csdn.net/slvher/article/details/9881171
https://blog.csdn.net/mj_lee/article/details/80703893