Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Printf
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Format specifier == Formatting of a value is specified as markup in the format string. For example, the following outputs <code>Your age is</code> and then the value of the variable {{var|age}} in decimal format. <syntaxhighlight lang="c"> printf("Your age is %d", age); </syntaxhighlight> ===Syntax=== The syntax for a format specifier is: %[''parameter''][''flags''][''width''][.''precision''][''length'']''type'' ===Parameter field=== The parameter field is optional. If included, then matching specifiers to values is {{em|not}} sequential. The numeric value {{samp|n}} selects the n-th value parameter. This is a [[POSIX]] extension; not [[C99]].{{needs citation|date=April 2025}} {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|''n''$}} | ''n'' is the index of the value parameter to [[serialization|serialize]] using this format specifier |} This field allows for using the same value multiple times in a format string instead of having to pass the value multiple times. If a specifier includes this field, then subsequent specifiers must also. For example, <syntaxhighlight lang="c"> printf("%2$d %2$#x; %1$d %1$#x",16,17); </syntaxhighlight> outputs: {{samp|17 0x11; 16 0x10}} This field is particularly useful for [[Localization (computing)|localizing]] messages to different [[natural language]]s that use different [[word order]]s. In [[Microsoft Windows API|Windows API]], support for this feature is via a different function, {{code|printf_p}}. ===Flags field=== The flags field can be zero or more of (in any order): {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|-}} |Left-align the output of this placeholder; default is to right-align the output |- | {{tt|+}} |Prepends a plus sign for a positive value; by default a positive value does not have a prefix |- | <code style="white-space:pre"> </code><br />(space) |Prepends a space character for a positive value; ignored if the {{tt|+}} flag exists; by default a positive value does not have a prefix |- | {{tt|0}} |When the 'width' option is specified, prepends zeros for numeric types; by prepends spaces; for example, {{code|printf("%4X",3)|c}} produces <samp style="white-space:pre">" 3"</samp>, while {{code|printf("%04X",3);|c}} produces {{samp|"0003"}} |- | {{tt|'}} | The integer or exponent of a decimal has the thousands grouping separator applied |- | {{tt|#}} | Alternate form:<br /> For {{tt|g}} and {{tt|G}} types, trailing zeros are not removed<br /> For {{tt|f}}, {{tt|F}}, {{tt|e}}, {{tt|E}}, {{tt|g}}, {{tt|G}} types, the output always contains a decimal point<br /> For {{tt|o}}, {{tt|x}}, {{tt|X}} types, the text {{tt|0}}, {{tt|0x}}, {{tt|0X}}, respectively, is prepended to non-zero numbers |} ===Width field=== The width field specifies the {{em|minimum}} number of characters to output. If the value can be represented in fewer characters, then the value is left-padded with spaces so that output is the number of characters specified. If the value requires more characters, then the output is longer than the specified width. A value is never truncated. For example, {{code|printf("%3d", 12);|c}} specifies a width of 3 and outputs {{samp|12}} with a space on the left to output 3 characters. The call {{code|printf("%3d", 1234);|c}} outputs {{samp|1234}} which is 4 characters long since that is the minimum width for that value even though the width specified is 3. If the width field is omitted, the output is the minimum number of characters for the value. If the field is specified as {{code|*}}, then the width value is read from the list of values in the call.<ref>{{cite web |title=printf |url=http://www.cplusplus.com/reference/cstdio/printf/ |access-date=2020-06-10 |website=cplusplus.com}}</ref> For example, {{code|printf("%*d", 3, 10);|c}} outputs <samp style="white-space:pre"> 10</samp> where the second parameter, {{code|3|c}}, is the width (matches with {{code|*}}) and {{code|10|c}} is the value to [[serialization|serialize]] (matches with {{code|d}}). Though not part of the width field, a leading zero is interpreted as the zero-padding flag mentioned above, and a negative value is treated as the positive value in conjunction with the left-alignment {{code|-}} flag also mentioned above. The width field can be used to format values as a table (tabulated output). But, columns do not align if any value is larger than fits in the width specified. For example, notice that the last line value ({{samp|1234}}) does not fit in the first column of width 3 and therefore the column is not aligned. <syntaxhighlight lang="output"> 1 1 12 12 123 123 1234 123 </syntaxhighlight> ===Precision field=== The precision field usually specifies a {{em|maximum}} limit of the output, depending on the particular formatting type. For [[floating-point]] numeric types, it specifies the number of digits to the right of the decimal point to which the output should be rounded; for {{code|%g}} and {{code|%G}} it specifies the total number of [[significant digits]] (before and after the decimal, not including leading or trailing zeroes) to round to. For the [[string (computer science)|string type]], it limits the number of characters that should be output, after which the string is truncated. The precision field may be omitted, or a numeric integer value, or a dynamic value when passed as another argument when indicated by an asterisk ({{code|*}}). For example, {{code|printf("%.*s", 3, "abcdef");|c}} outputs {{samp|abc}}. ===Length field=== The length field can be omitted or be any of: {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|hh}} | For integer types, causes {{tt|printf}} to expect an {{tt|int}}-sized integer argument which was promoted from a {{tt|char}}. |- | {{tt|h}} | For integer types, causes {{tt|printf}} to expect an {{tt|int}}-sized integer argument which was promoted from a {{tt|short}}. |- | {{tt|l}} | For integer types, causes {{tt|printf}} to expect a {{tt|long}}-sized integer argument. For floating-point types, this is ignored. {{tt|float}} arguments are always promoted to {{tt|double}} when used in a [[varargs]] call.<ref name="c99io">{{cite standard| publisher= [[International Organization for Standardization|ISO]]/[[International Electrotechnical Commission|IEC]] | year= 1999 | title-link= C99 | title= ISO/IEC 9899:1999(E): Programming Languages β C | section= 7.19.6.1 | at= para. 7 }}</ref> |- | {{tt|ll}} | For integer types, causes {{tt|printf}} to expect a {{tt|long long}}-sized integer argument. |- | {{tt|L}} | For floating-point types, causes {{tt|printf}} to expect a {{tt|long double}} argument. |- | {{tt|z}} | For integer types, causes {{tt|printf}} to expect a {{tt|size_t}}-sized integer argument. |- | {{tt|j}} | For integer types, causes {{tt|printf}} to expect a {{tt|intmax_t}}-sized integer argument. |- | {{tt|t}} | For integer types, causes {{tt|printf}} to expect a {{tt|ptrdiff_t}}-sized integer argument. |} Platform-specific length options came to exist prior to widespread use of the ISO C99 extensions, including: {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description ! ''Commonly found platforms'' |- | {{tt|I}} | For signed integer types, causes {{tt|printf}} to expect {{tt|ptrdiff_t}}-sized integer argument; for unsigned integer types, causes {{tt|printf}} to expect {{tt|size_t}}-sized integer argument. || [[Win32]]/[[Win64]] |- | {{tt|I32}} | For integer types, causes {{tt|printf}} to expect a 32-bit ([[double word]]) integer argument. || Win32/Win64 |- | {{tt|I64}} | For integer types, causes {{tt|printf}} to expect a 64-bit (quad word) integer argument. || Win32/Win64 |- | {{tt|q}} | For integer types, causes {{tt|printf}} to expect a 64-bit (quad word) integer argument. || [[BSD]] |} ISO C99 includes the <code>[[inttypes.h]]</code> header file that includes a number of [[Macro (computer science)|macros]] for platform-independent {{code|printf}} coding. For example: {{code|printf("%" PRId64, t);|c}} specifies decimal format for a [[Integer (computer science)|64-bit signed integer]]. Since the macros evaluate to a [[string literal]], and the compiler [[concatenates]] adjacent string literals, the expression {{code|"%" PRId64|c}} compiles to a single string. Macros include: {| class="wikitable" |- ! Macro ! Description |- | {{tt|PRId32}} | Typically equivalent to {{tt|I32d}} (''Win32/Win64'') or {{tt|d}} |- | {{tt|PRId64}} | Typically equivalent to {{tt|I64d}} (''Win32/Win64''), {{tt|lld}} (''32-bit platforms'') or {{tt|ld}} (''64-bit platforms'') |- | {{tt|PRIi32}} | Typically equivalent to {{tt|I32i}} (''Win32/Win64'') or {{tt|i}} |- | {{tt|PRIi64}} | Typically equivalent to {{tt|I64i}} (''Win32/Win64''), {{tt|lli}} (''32-bit platforms'') or {{tt|li}} (''64-bit platforms'') |- | {{tt|PRIu32}} | Typically equivalent to {{tt|I32u}} (''Win32/Win64'') or {{tt|u}} |- | {{tt|PRIu64}} | Typically equivalent to {{tt|I64u}} (''Win32/Win64''), {{tt|llu}} (''32-bit platforms'') or {{tt|lu}} (''64-bit platforms'') |- | {{tt|PRIx32}} | Typically equivalent to {{tt|I32x}} (''Win32/Win64'') or {{tt|x}} |- | {{tt|PRIx64}} | Typically equivalent to {{tt|I64x}} (''Win32/Win64''), {{tt|llx}} (''32-bit platforms'') or {{tt|lx}} (''64-bit platforms'') |} ===Type field=== The type field can be any of: {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|%}} |Output a literal {{tt|%}} character; does not accept flags, width, precision or length fields |- | {{tt|d}}, {{tt|i}} |(signed) {{tt|int}} formatted as decimal; {{tt|%d}} and {{tt|%i}} are synonymous except when used with <code>scanf</code> |- | {{tt|u}} | {{tt|unsigned int}} formatted as decimal. |- | {{tt|f}}, {{tt|F}} |{{tt|double}} formatted as [[Fixed-point arithmetic|fixed-point]]; {{tt|f}} and {{tt|F}} only differs in how the strings for an infinite number or [[NaN]] are printed ({{tt|inf}}, {{tt|infinity}} and {{tt|nan}} for {{tt|f}}; {{tt|INF}}, {{tt|INFINITY}} and {{tt|NAN}} for {{tt|F}}) |- | {{tt|e}}, {{tt|E}} |{{tt|double}} formatted as in exponential notation {{tt|''d''.''ddd''eΒ±''dd''}}; {{tt|E}} results in {{tt|E}} rather than {{tt|e}} to introduce the exponent; the exponent always contains at least two digits; if the value is zero, the exponent is {{tt|00}}; in Windows, the exponent contains three digits by default, e.g. {{tt|1.5e002}}, but this can be altered by Microsoft-specific {{code|_set_output_format}} function |- | {{tt|g}}, {{tt|G}} |{{tt|double}} formatted as either fixed-point or exponential notation, whichever is more appropriate for its magnitude; {{tt|g}} uses lower-case letters, {{tt|G}} uses upper-case letters; this type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included, and that the precision field specifies the total number of significant digits rather than the digits after the decimal; the decimal point is not included on whole numbers |- | {{tt|x}}, {{tt|X}} |{{tt|unsigned int}} formatted as [[hexadecimal]]; {{tt|x}} uses lower-case letters and {{tt|X}} uses upper-case |- | {{tt|o}} |{{tt|unsigned int}} formatted as [[octal]] |- | {{tt|s}} |null-terminated string |- | {{tt|c}} |{{tt|char}} |- | {{tt|p}} |[[Pointer (computer science)|Pointer]] formatted in an implementation-defined way |- | {{tt|a}}, {{tt|A}} |{{tt|double}} in hexadecimal notation, starting with {{tt|0x}} or {{tt|0X}}. {{tt|a}} uses lower-case letters, {{tt|A}} uses upper-case letters<ref>{{cite web| url= https://www.gnu.org/software/libc/manual/html_node/Table-of-Output-Conversions.html | work= The GNU C Library Reference Manual | at= sec. 12.12.3 | title= Table of Output Conversions | author= Free Software Foundation | author-link= Free Software Foundation | publisher= self-published | access-date=2014-03-17 }}</ref><ref> [http://www.cplusplus.com/reference/cstdio/printf/ "printf"] ({{tt|%a}} added in C99) </ref> |- | {{tt|n}} | Outputs nothing but writes the number of characters written so far into an integer [[Pointer (computer science)|pointer]] parameter; in [[Java (programming language)|Java]] this prints a [[newline]]<ref>{{cite web|url=https://docs.oracle.com/javase/tutorial/java/data/numberformat.html|title=Formatting Numeric Print Output |website=The Java Tutorials | publisher=Oracle Inc.|access-date=19 March 2018}}</ref> |} === Custom data type formatting === A common way to handle formatting with a custom data type is to format the custom data type value into a [[string (computer science)|string]], then use the {{code|%s|c}} specifier to include the serialized value in a larger message. Some printf-like functions allow extensions to the [[escape-character]]-based [[mini-language]], thus allowing the programmer to use a specific formatting function for non-builtin types. One is the (now [[deprecated]]) [[glibc]]'s [https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html {{code|register_printf_function()}}]. However, it is rarely used due to the fact that it conflicts with [[static program analysis|static format string checking]]. Another is [http://www.and.org/vstr/#cust-fmt Vstr custom formatters], which allows adding multi-character format names. Some applications (like the [[Apache HTTP Server]]) include their own printf-like function, and embed extensions into it. However these all tend to have the same problems that {{code|register_printf_function()}} has. The [[Linux kernel]] <code>[[printk]]</code> function supports a number of ways to display kernel structures using the generic {{code|%p|c}} specification, by {{em|appending}} additional format characters.<ref>{{cite web | url= https://docs.kernel.org/core-api/printk-formats.html | title= How to get printk format specifiers right | work = The Linux Kernel documentation | first1= Randy | last1= Dunlap | first2= Andrew | last2= Murray | publisher= [[Linux Foundation]] | date= n.d. | access-date= 2025-02-12 | archive-date= 2025-02-06 | archive-url= https://web.archive.org/web/20250206200419/https://docs.kernel.org/core-api/printk-formats.html | url-status= live }}</ref> For example, {{code|%pI4|c}} prints an [[IPv4 address]] in dotted-decimal form. This allows static format string checking (of the {{code|%p|c}} portion) at the expense of full compatibility with normal printf.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)