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;
}
请说明原因。
答案 0 :(得分:2)
You can find printf parameters。
如您所见%d
是有符号整数,在这种情况下整数表示32位。进一步转到说明符表,您将看到,要打印64位(long long
),您需要使用说明符ll
,因此您需要%lld
,不是%d
。
您的结果(-2147483648和0)为Undefined Behaviour
同样,我从评论中看到,您需要跨平台解决方案,因此您应该使用long long
而不是__int64
,因为这是Windows类型。
答案 1 :(得分:1)
您将两个long long
传递给期望两个int
的函数。将%d
和%i
更改为%ll
或将__int64
更改为int
。
答案 2 :(得分:1)
因此,正如其他答案所说,您通过将int64
传递给期望int
的格式字符串
相反,您应该使用stdint.h
和inttypes.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