C++ 为什么相同的vsnprintf代码在Windows(MSVC)和Unix(Clang)上的输出不同

C++ 为什么相同的vsnprintf代码在Windows(MSVC)和Unix(Clang)上的输出不同,c++,windows,unix,printf,C++,Windows,Unix,Printf,在Unix(Clang 3.8.1)上,此代码输出: 6:32 8:a8e 在Windows(MSVC 19.00.24215.1)上,此代码输出: 6:12345 6:a12345e #包括 #包括 静态std::string getFormattedString(const char*fmt,va_list ap){ int count=vsnprintf(NULL,0,fmt,ap)+1; std::cout正如@RaymondChen在评论中所说,vsnprintf修改ap。如果你想重用

在Unix(Clang 3.8.1)上,此代码输出:

6:32

8:a8e

在Windows(MSVC 19.00.24215.1)上,此代码输出:

6:12345

6:a12345e

#包括
#包括
静态std::string getFormattedString(const char*fmt,va_list ap){
int count=vsnprintf(NULL,0,fmt,ap)+1;

std::cout正如@RaymondChen在评论中所说,vsnprintf修改ap。如果你想重用va_列表,你必须使用va_copy制作一个副本:

static std::string getFormattedString(const char* fmt, va_list ap) {
    va_list ap2;
    va_copy(ap2, ap);
    int count = vsnprintf(NULL, 0, fmt, ap) + 1;
    std::cout << count << ": ";
    if (count <= 0) { return "unable to format message"; }

    std::string result = std::string(count, '\0');
    if (vsnprintf(&result[0], count, fmt, ap2) < 0) { return "error";}
    std::cout << result.size() << ' ' << strlen(result.c_str()) << '\n';

    return result;
}
static std::string getFormattedString(const char*fmt,va_list ap){
va_列表ap2;
副本(ap2,ap);
int count=vsnprintf(NULL,0,fmt,ap)+1;

std::你能用varargs重载函数名吗?@BoBTFish似乎你能,这是可以编译的fine@HBellamyUnix和Windows是操作系统,而不是编译器。请提及实际使用的编译器。
vsnprintf
修改
ap
,因此您两次调用它时,传递的是不同的
ap
@PaulMcKenzie抱歉,我认为
vsnprintf
的实际运行时实现不取决于编译器,而是取决于系统?不要忘记
va_end(ap2)
static std::string getFormattedString(const char* fmt, va_list ap) {
    va_list ap2;
    va_copy(ap2, ap);
    int count = vsnprintf(NULL, 0, fmt, ap) + 1;
    std::cout << count << ": ";
    if (count <= 0) { return "unable to format message"; }

    std::string result = std::string(count, '\0');
    if (vsnprintf(&result[0], count, fmt, ap2) < 0) { return "error";}
    std::cout << result.size() << ' ' << strlen(result.c_str()) << '\n';

    return result;
}