c++ - C++中sprintf函数的不同输出

标签 c++ c printf

sprintf 未正确显示字符串消息。要显示的消息是 值超出范围。范围是 -2147483648 和 2147483647。但是它被打印为 值超出范围。范围是 -2147483648 和 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;
}

请说明原因。

最佳答案

You can find printf parameters .

如您所见,%d 是有符号整数,本例中的整数表示 32 位。进一步查看说明符表,您会看到,要打印 64 位 (long long),您需要使用说明符 ll,因此您需要 %lld,而不是 %d


您的结果(-2147483648 和 0)是 Undefined Behaviour


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

关于c++ - C++中sprintf函数的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25137763/

相关文章:

c++ - 澄清 "object pool"模式?

c++ - 结构对齐和类型重新解释

c - Ansi C - 函数期望指向数组的指针

C、为什么printf在个位数长后添加 "D"?

c++ - 跨不同计算机识别设备

c++ - VS2008中如何开启 "auto-build"选项

将 getchar 与字符进行比较会返回警告并给我错误的代码

c - 这个 for 循环的条件是做什么的?

C: printf 未执行,可能的编译器优化?

c - 在C中,我想连续打印4个十进制数,然后打印接下来的4个