c语言可变参数的两种用法


#include <iostream>
#include <stdarg.h>
using namespace std;

int sum(char * msg, ...);
int my_vsprintf(char *buf, char *format, ...);

int main()
{
    sum("The sum of the list is:", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0);
    cout << endl;
    char buf[256];
    my_vsprintf(buf, "%My name is %s and I am %d years old.", "Ben", 24);
    cout << buf << endl;
    system("pause");
    return 0;
}

int sum(char *msg, ...)
{
    va_list st;
    va_start(st, msg);
    int total = 0;
    int tmp;
    while((tmp = va_arg(st, int)) != 0)
    {
        total += tmp;
    }
    va_end(st);
    cout << "The sum of the list is: " << total;
    return 0;
}

int my_vsprintf(char *buf, char *format, ...)
{
    va_list st;
    va_start(st, format);
    vsprintf(buf, format, st);
    /***************************************************************************/
    /*       函数名: vsprintf                                              
    /*       功 能: 送格式化输出到串中                                           
    /*       返回值: 正常情况下返回生成字串的长度(除去\0),错误情况返回负值             
    /*       用 法: int vsprintf(char *string, char *format, va_list param);   
    /*                将param 按格式format写入字符串string中                      
    /*       注: 该函数会出现内存溢出情况,建议使用vsnprintf                                                                            */
    /***************************************************************************/
    va_end(st);
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值