How to use C++ std::ostream with printf-like formatting?

前端 未结 8 2013

I am learning C++. cout is an instance of std::ostream class. How can I print a formatted string with it?

I can still use printf

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 07:32

    I suggest using ostringstream instead of ostream see following example :

    #include 
    #include 
    #include 
    #include "CppUnitTest.h"
    
    #define _CRT_NO_VA_START_VALIDATION
    
    std::string format(const std::string& format, ...)
    {
        va_list args;
        va_start(args, format);
        size_t len = std::vsnprintf(NULL, 0, format.c_str(), args);
        va_end(args);
        std::vector vec(len + 1);
        va_start(args, format);
        std::vsnprintf(&vec[0], len + 1, format.c_str(), args);
        va_end(args);
        return &vec[0];
    }
    

    example usage:

    std::ostringstream ss;
    ss << format("%s => %d", "Version", Version) << std::endl;
    Logger::WriteMessage(ss.str().c_str()); // write to unit test output
    std::cout << ss.str() << std::endl; // write to standard output
    

提交回复
热议问题