不同于c++中sprintf函数的输出

Different output from sprintf function in c++

本文关键字:输出 函数 sprintf c++ 不同于      更新时间:2023-10-16

sprintf没有正确显示字符串消息。显示的信息为Value out of range. Range is -2147483648 and 2147483647。然而,它被打印为Value out of range. Range is -2147483648 and 0 .

#include <iostream>
#include <string>
int main()
{
    __int64 tmpminVal = -2147483648;
    __int64 tmpmaxVal = 2147483647;
    std::string strTemp = "Value out of range. Range is %d and %i ";
    char buffer[100];
    int n = sprintf (buffer, strTemp.c_str(), tmpminVal,tmpmaxVal);
    strTemp = buffer;
    std::cout << strTemp << std::endl;
    return 0;
}

请提供这样做的原因

可以找到printf参数。

如您所见,%d是有符号整数,在这种情况下,整数表示32位。进一步查看说明符表,您将看到,要打印64位(long long),您需要使用说明符ll,因此您需要%lld,而不是%d


你的结果(-2147483648和0)是未定义行为


也正如我从评论中看到的,你想要跨平台的解决方案,所以你应该使用long long而不是__int64,因为这是Windows类型的

您将两个long long传递给需要两个int的函数。将%d%i更改为%ll或将__int64更改为int

所以,正如其他答案也说,通过将int64传递给期望int的格式字符串来调用未定义行为

应该使用stdint.hinttypes.h。在Linux上,这些将包括在内,在Windows下,您可以包括这个项目来使用它们:https://code.google.com/p/msinttypes/

一个例子是:

#include <iostream>
#include <string>
#include <inttypes.h>
#include <cstdint>
int main()
{
    int64_t tmpminVal = -2147483648;
    int64_t tmpmaxVal = 2147483647;
    std::string strTemp = "Value out of range. Range is %" PRId64 " and % " PRIi64 " ";
    char buffer[100];
    int n = sprintf (buffer, strTemp.c_str(), tmpminVal,tmpmaxVal);
    strTemp = buffer;
    std::cout << strTemp << std::endl;
    return 0;
}

您也可以在cppreference找到一些关于这些头文件的文档:http://en.cppreference.com/w/c/types/integer