std::string formatting like sprintf

前端 未结 30 2573
野趣味
野趣味 2020-11-22 04:42

I have to format std::string with sprintf and send it into file stream. How can I do this?

30条回答
  •  不思量自难忘°
    2020-11-22 05:24

    I wrote my own using vsnprintf so it returns string instead of having to create my own buffer.

    #include 
    #include 
    
    //missing string printf
    //this is safe and convenient but not exactly efficient
    inline std::string format(const char* fmt, ...){
        int size = 512;
        char* buffer = 0;
        buffer = new char[size];
        va_list vl;
        va_start(vl, fmt);
        int nsize = vsnprintf(buffer, size, fmt, vl);
        if(size<=nsize){ //fail delete buffer and try again
            delete[] buffer;
            buffer = 0;
            buffer = new char[nsize+1]; //+1 for /0
            nsize = vsnprintf(buffer, size, fmt, vl);
        }
        std::string ret(buffer);
        va_end(vl);
        delete[] buffer;
        return ret;
    }
    

    So you can use it like

    std::string mystr = format("%s %d %10.5f", "omg", 1, 10.5);
    

提交回复
热议问题