c语言实现不定参数调用

不定参数调用实现:

三个宏的使用va_arg()、va_start()和va_end()
上述的宏原型如下所示:
C代码 收藏代码

type va_arg(va_list argptr, type);  
void va_end(va_list argptr);  
void va_start(va_list argptr, last_parm);  

它们都包含在头文件stdarg.h中.

void fun(char *fmt,...){
    va_list ap;
    int d;
    double df;
    char *tmp=NULL,*va=NULL,c;
    char *last=NULL,*word=NULL,*msg=NULL;
    char varword[512];
    char res[512];
    va_start(ap,fmt);
    word=last=va=fmt;
    va++;/*because the d/c/s/f cant be the first and may cause bug*/
    while (*va) {
        switch (*va) {
        case 'd':
            tmp = va;
            while (*--tmp != '%' && tmp != last)
                ;
            if (tmp == last){
                /*in case the % is  the first character */
                if(last != fmt || *fmt!='%')
                    break;
            }
            strncpy(varword + strlen(varword), word, va - word + 1);
            d = va_arg(ap,int);
            sprintf(res, varword, d);
            strcpy(varword, res);
            last = tmp;
            word = va + 1;
            break;

        case 'c':
            tmp = va;
            while (*--tmp != '%' && tmp != last)
                ;
            if (tmp == last){
                if(last != fmt || *fmt!='%')
                    break;
            }
            strncpy(varword + strlen(varword), word, va - word + 1);
            c = va_arg(ap,char);
            sprintf(res, varword, c);
            strcpy(varword, res);
            last = tmp;
            word = va + 1;

            break;

        case 's':

            tmp = va;
            while (*--tmp != '%' && tmp != last)
                ;
            if (tmp == last){
                if(last != fmt || *fmt!='%')
                    break;
            }
            strncpy(varword + strlen(varword), word, va - word + 1);
            msg = va_arg(ap,char*);
            sprintf(res, varword, msg);
            strcpy(varword, res);
            last = tmp;
            word = va + 1;
            break;
        case 'f':
            tmp = va;
            while (*--tmp != '%' && tmp != last)
                ;
            if (tmp == last){
                if(last != fmt || *fmt!='%')
                    break;
            }
            strncpy(varword + strlen(varword), word, va - word + 1);
            df = va_arg(ap,double);
            sprintf(res, varword, df);
            strcpy(varword, res);
            last = tmp;
            word = va + 1;

            break;

        }
        va++;
    }
    va_end(ap);
    if(word!=va) strcat(res,word);
    printf("the result is :%s\n",res);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值