一般形式都是 type func(char * formatstr,...);

然后通过已有的参数 formatsrr 来推出,后面的参数。

这样写起来的话,就要匹配所有的基本类型,C++提供了3个宏和算法可以简单处理。

这样,通过vsprintf_s就格式化到buf中。

 

#include <iostream>
#include <stdarg.h>

void print(char * formatstr,...)  
{  
    char buf[1024] = {0};  

    va_list argptr;  
    va_start(argptr, formatstr);  
    vsprintf_s(buf,sizeof(buf),formatstr,argptr);
    std::cout<< buf << "strlen(buf) = " << strlen(buf) << std::endl;
    va_end(argptr);
}  

int main(){

    print("i=%c+%d\n",65,20);
    system("pause");
}

 

相关文章:

  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
猜你喜欢
  • 2022-02-07
  • 2021-11-16
  • 2021-06-28
  • 2021-11-03
相关资源
相似解决方案