可变参数的使用va_list

#include <stdarg.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <iostream>

std::string str_format(const char* format, ...)
{
    va_list ap;
    int size = getpagesize();
    char* buffer = new char[size]; 
    
    while(true){
       va_start(ap, format);
       int n = vsnprintf(buffer, size, format, ap);
       va_end(ap);
       if(n > -1 && n < size){
           break;
       }
       size *= 2;
       delete[] buffer;
       buffer = new char[size];
    }
    std::string str = buffer;
    delete[] buffer;
    return str;
}

int calc_sum(int num, ...)
{
    int iSum = 0;
    va_list ap;
    va_start(ap, num);
    while(num > 0) {
       iSum += va_arg(ap, int); 
       num--; 
    }
    va_end(ap);
    return iSum;
}

int main()
{
    std::string sStr = str_format("%d names: %s, %s", 2, "xu", "yan");
    std::cout << sStr << std::endl;

    std::cout << calc_sum(2, 1, 2) << std::endl;

    return 0;
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页