Reputation: 728
The sprintf is not displaying the string message appropriately. The message to be displayed is
Value out of range. Range is -2147483648 and 2147483647
. However it is printed as
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;
}
Please provide the reason why it is does so.
Upvotes: 0
Views: 596
Reputation: 81926
So, as the other answers also say, you're invoking undefined behavior by passing a int64
to a format string expecting an int
Instead, you should use stdint.h
and inttypes.h
. On Linux, these will be included, and under Windows, you can include this project to use them: https://code.google.com/p/msinttypes/
An example use would be:
#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;
}
You can also find some documentation about these header files at cppreference: http://en.cppreference.com/w/c/types/integer
Upvotes: 1
Reputation: 8946
You can find printf parameters.
As you see %d
is signed integer, integer in this case means 32-bit. Go further to specifiers table and you will see, that to print 64-bit (long long
) you need to use specifier ll
, so you need %lld
, not %d
.
Your result (-2147483648 and 0) is Undefined Behaviour
Also as I see from comments, you want cross platform solution, so you should use long long
instead of __int64
, as this one is Windows type.
Upvotes: 2
Reputation: 1606
You passing two long long
's to a function which expects two int
s. Either change %d
and %i
to %ll
or change __int64
to int
.
Upvotes: 1