不同于c++中sprintf函数的输出
Different output from sprintf function in c++
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.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
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 请解释"函数1(p1,p2,p3);"的输出
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 当使用通配符和null指针调用函数时,对输出的说明
- 为什么递归函数的最终输出是 5?
- C++ 构造函数未显示输出
- c++ 将成员函数的输出写入文本文件
- 简单函数并不总是返回预期的输出
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- GCC 仪器 - 是否可以自动输出函数的参数?
- 意外输出..函数绑定在虚拟表中的发生方式
- 输出函数调用日志文件
- C++:程序不输出函数返回值
- 通用化标准库容器的输出函数
- C++:int数组[a][b][C]={0};未将所有值设置为0.是那个指令错了,还是我的输出函数出了问题
- <</>>运算符重载和输入/输出函数之间的区别
- Ncurses 输出函数只接受常量数据