std::string formatting like sprintf

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

    If you are on a system that has asprintf(3), you can easily wrap it:

    #include 
    #include 
    #include 
    
    std::string format(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
    
    std::string format(const char *fmt, ...)
    {
        std::string result;
    
        va_list ap;
        va_start(ap, fmt);
    
        char *tmp = 0;
        int res = vasprintf(&tmp, fmt, ap);
        va_end(ap);
    
        if (res != -1) {
            result = tmp;
            free(tmp);
        } else {
            // The vasprintf call failed, either do nothing and
            // fall through (will return empty string) or
            // throw an exception, if your code uses those
        }
    
        return result;
    }
    
    int main(int argc, char *argv[]) {
        std::string username = "you";
        std::cout << format("Hello %s! %d", username.c_str(), 123) << std::endl;
        return 0;
    }
    

提交回复
热议问题