不定参数的格式化

#include<cstdarg>
#include<cstdio>
std::string formatt(const char * format,...)
{
    va_list args;
    (void)va_start(args,format);

    std::string retstr;

    size_t size = 1024;
    while(size <= 10*1024*1024)
    {
        char * buf = new char[size];
        memset(buf,0,size);

        int ret = vsnprintf(buf,size,(const char *)format,args);
        if(ret <= -1 || ret >=  (int)size)
        {
            size = size<<1;
            delete[] buf;
            continue;
        }

        retstr.assign(buf);
        delete[] buf;
        break;
    }

    va_end(args);

    return retstr;
}


int main()
{
    int id  = 12;
    std::string cc = "myname is xiaohan";
    std::string str_cc = formatt(" msg : %s. myid is %d ,",cc.c_str(),id);
    std::cout << str_cc << std::endl;
    return 0;
}

posted on 2014-07-31 14:13  leafs  阅读(190)  评论(0编辑  收藏  举报

导航