字符串变参格式化

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
using namespace std;

// https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/vscprintf-vscprintf-l-vscwprintf-vscwprintf-l?view=msvc-170&devlangs=cpp&f1url=%3FappId%3DDev14IDEF1%26l%3DEN-US%26k%3Dk(STDIO%252F_vscprintf)%3Bk(_vscprintf)%3Bk(DevLang-C%252B%252B)%3Bk(TargetOS-Windows)%26rd%3Dtrue
//https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/vsprintf-s-vsprintf-s-l-vswprintf-s-vswprintf-s-l?view=msvc-170&devlangs=cpp&f1url=%3FappId%3DDev14IDEF1%26l%3DEN-US%26k%3Dk(STDIO%252Fvsprintf_s)%3Bk(vsprintf_s)%3Bk(DevLang-C%252B%252B)%3Bk(TargetOS-Windows)%26rd%3Dtrue
//https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/vsprintf-vsprintf-l-vswprintf-vswprintf-l-vswprintf-l?view=msvc-170
std::string StringFormat(const char* format, ...) {
    va_list args = nullptr;
    va_start(args, format);
    // Returns the number of characters in the formatted string using a pointer to a list of arguments.
    size_t size = _vscprintf(format, args) + 1;
    char* buf = new char[size];
    memset(buf, 0, size);
    vsprintf_s(buf, size, format, args);
    std::string str_tmp(buf);
    delete[] buf;
    buf = nullptr;
    va_end(args);
    return str_tmp;
}

int main() {
    int64_t i64 = 111;    // 32位操作系统下,int格式化为%lld会存在异常!!!
    string str = StringFormat("String format test, int:%d, int64:%lld, float: %f, char*:%s",
        1, i64, 3.1, "456");
    cout << str << endl;
    getchar();
    return 0;
}

你可能感兴趣的:(C++,c++)