std::string formatting like sprintf

前端 未结 30 2563
野趣味
野趣味 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:27

    This is the code I use to do this in my program... It's nothing fancy, but it does the trick... Note, you will have to adjust your size as applicable. MAX_BUFFER for me is 1024.

    std::string Format ( const char *fmt, ... )
    {
        char textString[MAX_BUFFER*5] = {'\0'};
    
        // -- Empty the buffer properly to ensure no leaks.
        memset(textString, '\0', sizeof(textString));
    
        va_list args;
        va_start ( args, fmt );
        vsnprintf ( textString, MAX_BUFFER*5, fmt, args );
        va_end ( args );
        std::string retStr = textString;
        return retStr;
    }
    

提交回复
热议问题