Possible Duplicate:
How do you printf an unsigned long long int?
#include <cstdio>
int main ()
{
unsigned long long int n;
scanf("%llu",&n);
printf("n: %llu\n",n);
n /= 3;
printf("n/3: %llu\n",n);
return 0;
}
Whatever I put in input, I get very strange output, for example:
n: 1
n/3: 2863311531
or
n: 2
n/3: 2863311531
or
n: 1000
n/3: 2863311864
What's the reason? How should I do this correctly?
(g++ 3.4.2, Win XP)
The problem is that MinGW relies on the msvcrt.dll
runtime. Even though the GCC compiler supports C99-isms like long long
the runtime which is processing the format string doesn't understand the "%llu"
format specifier.
You'll need to use Microsoft's format specifier for 64-bit ints. I think that "%I64u"
will do the trick.
If you #include <inttypes.h>
you can use the macros it provides to be a little more portable:
int main ()
{
unsigned long long int n;
scanf("%"SCNu64, &n);
printf("n: %"PRIu64"\n",n);
n /= 3;
printf("n/3: %"PRIu64"\n",n);
return 0;
}
Note that MSVC doesn't have inttypes.h
until VS 2010, so if you want to be portable to those compilers you'll need to dig up your own copy of inttypes.h
or take the one from VS 2010 (which I think will work with earlier MSVC compilers, but I'm not entirely sure). Then again, to be portable to those compilers, you'd need to do something similar for the unsigned long long
declaration, which would entail digging up stdint.h
and using uint64_t
instead of unsigned long long
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With