I know this doesn't sound productive, but I'm looking for a way to remember all of the formatting codes for printf
calls. %s
, %p
, %f
are all obvious, but I can't understand where %d
comes from. Is %i
already taken by something else?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
http://en.wikipedia.org/wiki/Printf_format_string seems to say that it's for decimal as I had guessed
d,i
It stands for "decimal" (base 10), not "integer." You can use
%x
to print in hexadecimal (base 16), and%o
to print in octal (base 8). An integer could be in any of these bases.In
printf()
, you can use%i
as a synonym for%d
, if you prefer to indicate "integer" instead of "decimal," but%d
is generally preferred as it's more specific.On input, using
scanf()
, you can use use both%i
and%d
as well.%i
means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a0
or0x
prefix), while%d
means parse it as a decimal integer.Here's an example of all of them in action:
So, you should only use
%i
if you want the input base to depend on the prefix; if the input base should be fixed, you should use%d
,%x
, or%o
. In particular, the fact that a leading0
puts you in octal mode can catch you up.