gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:20 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com