Składnia specyfikacji formatu: funkcje printf i wprintfFormat specification syntax: printf and wprintf functions
Różne printf
i wprintf
funkcje przyjmują ciąg formatu i opcjonalne argumenty i tworzą sformatowaną sekwencję znaków dla danych wyjściowych.The various printf
and wprintf
functions take a format string and optional arguments and produce a formatted sequence of characters for output. Ciąg formatu zawiera zero lub więcej dyrektyw , które są znakami literału dla danych wyjściowych lub zakodowanych specyfikacji konwersji , które opisują sposób formatowania argumentu w danych wyjściowych.The format string contains zero or more directives , which are either literal characters for output or encoded conversion specifications that describe how to format an argument in the output. W tym artykule opisano składnię używaną do kodowania specyfikacji konwersji w ciągu formatu.This article describes the syntax used to encode conversion specifications in the format string. Aby uzyskać listę tych funkcji, zobacz przesyłanie strumieniowe we/wy.For a listing of these functions, see Stream I/O.
Specyfikacja konwersji składa się z pól opcjonalnych i wymaganych w tej postaci:A conversion specification consists of optional and required fields in this form:
% [ flagi] [ Szerokość] [. precyzja] [ rozmiar] Typ% [ flags][ width][. precision][ size] type
Każde pole specyfikacji konwersji jest znakiem lub cyfrą, która oznacza określoną opcję formatu lub specyfikator konwersji.Each field of the conversion specification is a character or a number that signifies a particular format option or conversion specifier. Pole wymagany Typ określa rodzaj konwersji, która ma zostać zastosowana do argumentu.The required type field specifies the kind of conversion to be applied to an argument. Opcjonalne flagi , Szerokość i precyzja kontrolują dodatkowe aspekty formatowania, takie jak spacje wiodące lub zera, uzasadnienie i wyświetlana dokładność.The optional flags , width , and precision fields control additional format aspects such as leading spaces or zeroes, justification, and displayed precision. Pole rozmiar określa rozmiar zużytego i przekonwertowanego argumentu.The size field specifies the size of the argument consumed and converted.
Podstawowa specyfikacja konwersji zawiera tylko znak procentu i Typ .A basic conversion specification contains only the percent sign and a type character. Na przykład %s
określa konwersję ciągu.For example, %s
specifies a string conversion. Aby znak procentu był wyświetlany, należy użyć składni %%
.To print a percent-sign character, use %%
. Jeśli po znaku procentu następuje znak, który nie ma znaczenia jako pola formatu, zostanie wywołana procedura obsługi nieprawidłowego parametru.If a percent sign is followed by a character that has no meaning as a format field, the invalid parameter handler is invoked. Aby uzyskać więcej informacji, zobacz Walidacja parametrów.For more information, see Parameter Validation.
Ważne
W celu zapewnienia bezpieczeństwa i stabilności upewnij się, że ciągi specyfikacji konwersji nie są zdefiniowane przez użytkownika.For security and stability, ensure that conversion specification strings are not user-defined. Rozważmy na przykład program, który monituje użytkownika o wprowadzenie nazwy, a dane wejściowe przechowuje w zmiennej o nazwie user_name
będącej ciągiem tekstowym.For example, consider a program that prompts the user to enter a name and stores the input in a string variable that's named user_name
. W celu wyświetlenia wartości zmiennej user_name
nie należy robić tak:To print user_name
, do not do this:
printf( user_name ); /* Danger! If user_name contains "%s", program will crash */
Zamiast tego należy zrobić tak:Instead, do this:
printf( "%s", user_name );
Uwaga
W programie Visual Studio 2015 printf
i scanf
Rodzina funkcji zostały zadeklarowane jako inline
i przenoszone do <stdio.h>
<conio.h>
nagłówków i.In Visual Studio 2015 The printf
and scanf
family of functions were declared as inline
and moved to the <stdio.h>
and <conio.h>
headers. W przypadku migrowania starszego kodu w połączeniu z tymi funkcjami może być widoczny LNK2019 .If you are migrating older code you might see LNK2019 in connection with these functions. Aby uzyskać więcej informacji, zobacz Visual C++ historię zmian 2003-2015.For more information, see Visual C++ change history 2003 - 2015.
Specyfikator konwersji typówType conversion specifier
Znak specyfikatora konwersji typu określa, czy odpowiedni argument ma być interpretowany jako znak, ciąg, wskaźnik, liczba całkowita, czy liczba zmiennoprzecinkowa.The type conversion specifier character specifies whether to interpret the corresponding argument as a character, a string, a pointer, an integer, or a floating-point number. Znak typu jest jedynym wymaganym polem specyfikacji konwersji i pojawia się po dowolnych opcjonalnych polach.The type character is the only required conversion specification field, and it appears after any optional fields.
Argumenty występujące po ciągu formatu są interpretowane według odpowiedniego znaku typu i opcjonalnego prefiksu rozmiaru .The arguments that follow the format string are interpreted according to the corresponding type character and the optional size prefix. Konwersje dla typów znaków char
i wchar_t
są określone za pomocą znaków c
lub C
, oraz ciągów z pojedynczym bajtem lub szeroką literą, w zależności od tego, s
S
która funkcja formatowania jest używana.Conversions for character types char
and wchar_t
are specified by using c
or C
, and single-byte and multi-byte or wide character strings are specified by using s
or S
, depending on which formatting function is being used. Argumenty znaków i ciągów, które są określone za pomocą c
i s
są interpretowane jako char
i char*
przez printf
funkcje rodzinne lub jako wchar_t
i wchar_t*
przez wprintf
funkcje rodzinne.Character and string arguments that are specified by using c
and s
are interpreted as char
and char*
by printf
family functions, or as wchar_t
and wchar_t*
by wprintf
family functions. Argumenty znaków i ciągów, które są określone za pomocą C
i S
są interpretowane jako wchar_t
i wchar_t*
przez printf
funkcje rodzinne lub jako char
i char*
przez wprintf
funkcje rodzinne.Character and string arguments that are specified by using C
and S
are interpreted as wchar_t
and wchar_t*
by printf
family functions, or as char
and char*
by wprintf
family functions. To zachowanie jest zależne od firmy Microsoft.This behavior is Microsoft-specific.
Typy całkowite, takie jak short
, int
,, long
long long
i ich unsigned
warianty, są określane przy użyciu d
, i
,,, o
u
x
i X
.Integer types such as short
, int
, long
, long long
, and their unsigned
variants, are specified by using d
, i
, o
, u
, x
, and X
. Typy zmiennoprzecinkowe, takie jak float
, double
, i long double
, są określane przy użyciu a
, A
, e
,, E
,, f
F
g
i G
.Floating-point types such as float
, double
, and long double
, are specified by using a
, A
, e
, E
, f
, F
, g
, and G
. Domyślnie, chyba że są modyfikowane przez prefiks rozmiaru , argumenty całkowite są przekształcane na int
Typ, a argumenty zmiennoprzecinkowe są przekształcane na double
.By default, unless they're modified by a size prefix, integer arguments are coerced to int
type, and floating-point arguments are coerced to double
. W systemach 64-bitowych int
jest wartością 32-bitową, dlatego 64-bitowe liczby całkowite będą obcinane, gdy są formatowane do danych wyjściowych, chyba że jest używany ll prefiks size I64 .On 64-bit systems, an int
is a 32-bit value; so, 64-bit integers will be truncated when they're formatted for output unless a size prefix of ll or I64 is used. Typy wskaźników, które są określone przy p
użyciu domyślnego rozmiaru wskaźnika dla platformy.Pointer types that are specified by p
use the default pointer size for the platform.
Uwaga
Specyficzne dla firmy Microsoft:Microsoft-specific:
Z
Typ znaku oraz zachowanie c
C
znaków,, i, gdy są s
S
używane razem z printf
wprintf
funkcjami i są rozszerzeniami firmy Microsoft.The Z
type character, and the behavior of the c
, C
, s
, and S
type characters when they're used with the printf
and wprintf
functions, are Microsoft extensions. Standard ISO C używa c
i s
konsekwentnie w przypadku wąskich znaków i ciągów C
oraz S
dla szerokich znaków i ciągów, we wszystkich funkcjach formatowania.The ISO C standard uses c
and s
consistently for narrow characters and strings, and C
and S
for wide characters and strings, in all formatting functions.
Znaki pola typuType field characters
Znak typuType character | ArgumentArgument | Format danych wyjściowychOutput format |
---|---|---|
c |
ZnakCharacter | Gdy jest używany z printf funkcjami, określa znak jednobajtowy; gdy jest używany z wprintf funkcjami, określa szeroki znak.When used with printf functions, specifies a single-byte character; when used with wprintf functions, specifies a wide character. |
C |
ZnakCharacter | Gdy jest używany z printf funkcjami, określa znak wprintf dwubajtowy; gdy jest używany z funkcjami, określa znak pojedynczy.When used with printf functions, specifies a wide character; when used with wprintf functions, specifies a single-byte character. |
d |
Liczba całkowitaInteger | Cyfra dziesiętna ze znakiem.Signed decimal integer. |
i |
Liczba całkowitaInteger | Cyfra dziesiętna ze znakiem.Signed decimal integer. |
o |
Liczba całkowitaInteger | Liczba całkowita bez znaku.Unsigned octal integer. |
u |
Liczba całkowitaInteger | Liczba całkowita dziesiętna bez znaku.Unsigned decimal integer. |
x |
Liczba całkowitaInteger | Szesnastkowa liczba całkowita bez znaku; używa " abcdef ".Unsigned hexadecimal integer; uses "abcdef ". |
X |
Liczba całkowitaInteger | Szesnastkowa liczba całkowita bez znaku; używa " ABCDEF ".Unsigned hexadecimal integer; uses "ABCDEF ". |
e |
Liczba zmiennoprzecinkowaFloating-point | Podpisana wartość, która ma postać [-] d.dddd e ± dd [ d ], gdzie d jest jedną cyfrą dziesiętną, dddd jest co najmniej jedną cyfrą dziesiętną, w zależności od określonej precyzji lub sześć domyślnie, i dd [ d ] ma dwie lub trzy cyfry dziesiętne, w zależności od formatu danych wyjściowych i rozmiaru wykładnika.Signed value that has the form [-] d.dddd e±dd [d ], where d is one decimal digit, dddd is one or more decimal digits depending on the specified precision, or six by default, and dd [d ] is two or three decimal digits depending on the output format and size of the exponent. |
E |
Liczba zmiennoprzecinkowaFloating-point | Identyczny z e formatem, z wyjątkiem tego, że E nie e wprowadza wykładnika.Identical to the e format except that E rather than e introduces the exponent. |
f |
Liczba zmiennoprzecinkowaFloating-point | Podpisana wartość, która ma postać [-] dddd . dddd , gdzie dddd jest co najmniej jedną cyfrą dziesiętną.Signed value that has the form [-] dddd .dddd , where dddd is one or more decimal digits. Liczba cyfr przed punktem dziesiętnym zależy od wielkości liczby, a liczba cyfr po przecinku jest zależna od wymaganej precyzji lub sześciu domyślnie.The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision, or six by default. |
F |
Liczba zmiennoprzecinkowaFloating-point | Identyczny z f formatem, z wyjątkiem tego, że nieskończoność i Nan dane wyjściowe są pisane wielkimi literami.Identical to the f format except that infinity and nan output is capitalized. |
g |
Liczba zmiennoprzecinkowaFloating-point | Wartości podpisane są wyświetlane w f e formacie lub, w zależności od tego, który jest bardziej zwarty dla danej wartości i dokładności.Signed values are displayed in f or e format, whichever is more compact for the given value and precision. e Format jest używany tylko wtedy, gdy wykładnik wartości jest mniejszy niż-4 lub większy lub równy argumentowi precyzji .The e format is used only when the exponent of the value is less than -4 or greater than or equal to the precision argument. Końcowe zera są obcinane, a punkt dziesiętny pojawia się tylko wtedy, gdy jedna lub więcej cyfr należy do niego.Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it. |
G |
Liczba zmiennoprzecinkowaFloating-point | Identyczny z g formatem, z tą różnicą, że E zamiast e , wprowadza wykładnik (tam, gdzie to konieczne).Identical to the g format, except that E , rather than e , introduces the exponent (where appropriate). |
a |
Liczba zmiennoprzecinkowaFloating-point | Podpisana szesnastkowa wartość zmiennoprzecinkowa o podwójnej precyzji, która ma postać [-] 0xh. hhhhp ± dd , gdzie h. hhhh to cyfry szesnastkowe (przy użyciu małych liter) mantysy i dd są jedną lub większą cyfrą wykładnika.Signed hexadecimal double-precision floating-point value that has the form [-]0xh.hhhhp±dd , where h.hhhh are the hex digits (using lower case letters) of the mantissa, and dd are one or more digits for the exponent. Precyzja określa liczbę cyfr po punkcie.The precision specifies the number of digits after the point. |
A |
Liczba zmiennoprzecinkowaFloating-point | Podpisana szesnastkowa wartość zmiennoprzecinkowa o podwójnej precyzji, która ma postać [-] 0Xh. hhhhP ± dd , gdzie h. hhhh to cyfry szesnastkowe (przy użyciu wielkich liter) mantysy, a DD to jedna lub więcej cyfr dla wykładnika.Signed hexadecimal double-precision floating-point value that has the form [-]0Xh.hhhhP±dd , where h.hhhh are the hex digits (using capital letters) of the mantissa, and dd are one or more digits for the exponent. Precyzja określa liczbę cyfr po punkcie.The precision specifies the number of digits after the point. |
n |
Wskaźnik na liczbę całkowitąPointer to integer | Liczba znaków, które zostały pomyślnie wpisane do strumienia lub buforu.Number of characters that are successfully written so far to the stream or buffer. Ta wartość jest przechowywana w postaci liczby całkowitej, której adres jest podawany jako argument.This value is stored in the integer whose address is given as the argument. Rozmiar liczby całkowitej wskazywanej w można kontrolować przy użyciu prefiksu specyfikacji rozmiaru argumentu.The size of the integer pointed at can be controlled by an argument size specification prefix. n Specyfikator jest domyślnie wyłączony. Aby uzyskać więcej informacji, zobacz ważne uwagi dotyczące zabezpieczeń.The n specifier is disabled by default; for information see the important security note. |
p |
Typ wskaźnikaPointer type | Wyświetlaj argument jako adres w cyfrach szesnastkowych.Display the argument as an address in hexadecimal digits. |
s |
StringString | Gdy jest używany z printf funkcjami, określa dwubajtowy lub wielobajtowy ciąg znaków; gdy jest używany z wprintf funkcjami, określa ciąg znaków szerokich.When used with printf functions, specifies a single-byte or multi-byte character string; when used with wprintf functions, specifies a wide-character string. Znaki są wyświetlane do pierwszego znaku null lub do czasu osiągnięcia wartości precyzji .Characters are displayed up to the first null character or until the precision value is reached. |
S |
StringString | Gdy jest używany z printf funkcjami, określa ciąg znaków dwubajtowych; gdy jest używany z wprintf funkcjami, określa ciąg znaków o pojedynczym bajcie lub wielobajtowym.When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-byte or multi-byte character string. Znaki są wyświetlane do pierwszego znaku null lub do czasu osiągnięcia wartości precyzji .Characters are displayed up to the first null character or until the precision value is reached. |
Z |
ANSI_STRING lub UNICODE_STRING StrukturaANSI_STRING or UNICODE_STRING structure |
Gdy ANSI_STRING UNICODE_STRING jako argument jest przekazanie adresu lub struktury, Wyświetl ciąg zawarty w buforze wskazywanym przez Buffer pole struktury.When the address of an ANSI_STRING or UNICODE_STRING structure is passed as the argument, display the string contained in the buffer pointed to by the Buffer field of the structure. Użyj prefiksu modyfikatora rozmiaru , w Aby określić UNICODE_STRING argument — na przykład %wZ .Use a size modifier prefix of w to specify a UNICODE_STRING argument—for example, %wZ . Length W polu struktury musi być ustawiona Długość (w bajtach) ciągu.The Length field of the structure must be set to the length, in bytes, of the string. MaximumLength W polu struktury musi być ustawiona Długość (w bajtach) buforu.The MaximumLength field of the structure must be set to the length, in bytes, of the buffer.Zazwyczaj Z znak typu jest używany tylko w funkcjach debugowania sterowników, które używają specyfikacji konwersji, takich jak dbgPrint i kdPrint .Typically, the Z type character is used only in driver debugging functions that use a conversion specification, such as dbgPrint and kdPrint . |
Począwszy od programu Visual Studio 2015, jeśli argument, który odpowiada specyfikatorowi konwersji zmiennoprzecinkowej (,,,,,, a
A
e
E
f
F
g
G
) jest nieskończony, nieokreślony lub NaN, sformatowane dane wyjściowe są zgodne ze standardem C99.Starting in Visual Studio 2015, if the argument that corresponds to a floating-point conversion specifier ( a
, A
, e
, E
, f
, F
, g
, G
) is infinite, indefinite, or NaN, the formatted output conforms to the C99 standard. W tej tabeli wymieniono sformatowane dane wyjściowe:This table lists the formatted output:
WartośćValue | Dane wyjścioweOutput |
---|---|
nieskończonośćinfinity | inf |
Cichy NaNQuiet NaN | nan |
Sygnalizowanie NaNSignaling NaN | nan(snan) |
Nieokreślony NaNIndefinite NaN | nan(ind) |
Wszystkie te wartości mogą być poprzedzone znakiem.Any of these values may be prefixed by a sign. Jeśli znak specyfikatora konwersji typu zmiennoprzecinkowego jest wielką literą, dane wyjściowe są również formatowane wielkimi literami.If a floating-point type conversion specifier character is a capital letter, then the output is also formatted in capital letters. Na przykład jeśli specyfikator formatu jest %F
zamiast %f
, nieskończoność jest formatowana jako INF
zamiast inf
.For example, if the format specifier is %F
instead of %f
, an infinity is formatted as INF
instead of inf
. scanf
Funkcje te mogą również analizować te ciągi, dzięki czemu te wartości mogą przekonywać rundy printf
i scanf
funkcje.The scanf
functions can also parse these strings, so these values can make a round trip through printf
and scanf
functions.
Przed uruchomieniem programu Visual Studio 2015 CRT użył innego niestandardowego formatu dla danych wyjściowych nieskończonych, nieokreślonych i NaN:Before Visual Studio 2015, the CRT used a different, non-standard format for output of infinite, indefinite, and NaN values:
WartośćValue | Dane wyjścioweOutput |
---|---|
+ nieskończoność+ infinity | 1.#INF cyfry losowe1.#INF random-digits |
-nieskończoność- infinity | -1.#INF cyfry losowe-1.#INF random-digits |
Nieokreślony (taki sam jak cichy NaN)Indefinite (same as quiet NaN) | cyfra .#IND cyfry losowedigit .#IND random-digits |
NaNNaN | cyfra .#NAN cyfry losowedigit .#NAN random-digits |
Dowolne z tych elementów mogło zostać poprzedzone znakiem i być sformatowane w różny sposób w zależności od szerokości pola i precyzji, czasami z nietypowymi skutkami.Any of these may have been prefixed by a sign, and may have been formatted differently depending on field width and precision, sometimes with unusual effects. Na przykład printf("%.2f\n", INFINITY)
drukuje, 1.#J
ponieważ #INF będzie "zaokrąglona" do dwóch cyfr precyzji.For example, printf("%.2f\n", INFINITY)
prints 1.#J
because the #INF would be "rounded" to two digits of precision.
Uwaga
Jeśli argument, który odnosi się do %s
lub %S
lub Buffer
pola argumentu, który odpowiada %Z
, jest wskaźnikiem typu null, zostanie wyświetlony komunikat "(null)".If the argument that corresponds to %s
or %S
, or the Buffer
field of the argument that corresponds to %Z
, is a null pointer, "(null)" is displayed.
Uwaga
We wszystkich formatach wykładniczych minimalna liczba cyfr do wyświetlenia jest równa 2, przy użyciu trzech tylko w razie potrzeby.In all exponential formats, the minimum number of digits of exponent to display is two, using three only if necessary. Korzystając z _set_output_format
funkcji, można ustawić liczbę wyświetlanych cyfr na trzy w celu zapewnienia zgodności z kodem zapisanym dla Visual Studio 2013 i przed.By using the _set_output_format
function, you can set the number of digits displayed to three for backward compatibility with code written for Visual Studio 2013 and before.
Ważne
Ponieważ %n
Format jest z natury niezabezpieczony, jest domyślnie wyłączony.Because the %n
format is inherently insecure, it's disabled by default. Jeśli %n
wystąpi w ciągu formatu, zostanie wywołana procedura obsługi nieprawidłowego parametru, zgodnie z opisem w walidacji parametru.If %n
is encountered in a format string, the invalid parameter handler is invoked, as described in Parameter Validation. Aby włączyć %n
obsługę, zobacz _set_printf_count_output
.To enable %n
support, see _set_printf_count_output
.
Dyrektywy flagFlag directives
Pierwsze opcjonalne pole w specyfikacji konwersji zawiera dyrektywy flag , zero lub więcej znaków flagi, które określają Justowanie danych wyjściowych i kontrolowanie danych wyjściowych znaków, pustych, wiodących zer, punktów dziesiętnych i szesnastkowych prefiksów.The first optional field in a conversion specification contains flag directives , zero or more flag characters that specify output justification and control output of signs, blanks, leading zeros, decimal points, and octal and hexadecimal prefixes. W specyfikacji konwersji może pojawić się więcej niż jedna dyrektywa flag, a znaki flagi mogą pojawiać się w dowolnej kolejności.More than one flag directive may appear in a conversion specification, and the flag characters can appear in any order.
Znaki flagiFlag characters
FlagaFlag | ZnaczenieMeaning | DomyślneDefault |
---|---|---|
- |
Wyrównaj wynik z lewej strony do pola.Left align the result within the given field width. | Wyrównaj do prawej.Right align. |
+ |
Użyj znaku (+ lub-), aby utworzyć prefiks wartości wyjściowej, jeśli jest ona typu ze znakiem.Use a sign (+ or -) to prefix the output value if it's of a signed type. | Znak jest wyświetlany tylko w przypadku ujemnych wartości podpisanych (-).Sign appears only for negative signed values (-). |
0 |
Jeśli Szerokość jest poprzedzona znakiem 0 , zera wiodące są dodawane do momentu osiągnięcia minimalnej szerokości.If width is prefixed by 0 , leading zeros are added until the minimum width is reached. Jeśli oba 0 i - pojawiają się, 0 jest ignorowany.If both 0 and - appear, the 0 is ignored. Jeśli 0 jest określony dla formatu liczb całkowitych ( i ,,,, u x X o , d ) i specyfikacji precyzji, na przykład %04.d — 0 jest ignorowany.If 0 is specified for an integer format ( i , u , x , X , o , d ) and a precision specification is also present—for example, %04.d —the 0 is ignored. Jeśli 0 jest określony dla a formatu lub A zmiennoprzecinkowego, zera wiodące są poprzedzone mantysy po 0x 0X prefiksie lub.If 0 is specified for the a or A floating-point format, leading zeros are prepended to the mantissa, after the 0x or 0X prefix. |
Brak dopełnienia.No padding. |
puste (' ')blank (' ') | Użyj pustej wartości, aby prefiksować wartość wyjściową, jeśli jest ona podpisana i dodatnia.Use a blank to prefix the output value if it's signed and positive. Wartość pusta jest ignorowana, jeśli są wyświetlane flagi puste i +.The blank is ignored if both the blank and + flags appear. | Nie pojawia się żadne puste.No blank appears. |
# |
Gdy jest używany z o , x , lub w X formacie, # Flaga używa 0 0x odpowiednio,, lub 0X , aby prefiksować dowolną wartość wyjściową różną od zera.When it's used with the o , x , or X format, the # flag uses 0 , 0x , or 0X , respectively, to prefix any nonzero output value. |
Nie pojawia się żadne puste.No blank appears. |
Gdy jest używany z e , E ,,,, lub w f F a A formacie, # flaga wymusza wartość wyjściową, aby zawierała separator dziesiętny.When it's used with the e , E , f , F , a , or A format, the # flag forces the output value to contain a decimal point. |
Punkt dziesiętny jest wyświetlany tylko wtedy, gdy cyfry są zgodne.Decimal point appears only if digits follow it. | |
Gdy jest używany z g G formatem lub, # flaga wymusza wartość wyjściową, aby zawierała przecinek dziesiętny i uniemożliwia obcinanie końcowych zer.When it's used with the g or G format, the # flag forces the output value to contain a decimal point and prevents the truncation of trailing zeros.Ignorowane, gdy jest używany z c , d , i ,, u lub s .Ignored when used with c , d , i , u , or s . |
Punkt dziesiętny jest wyświetlany tylko wtedy, gdy cyfry są zgodne.Decimal point appears only if digits follow it. Końcowe zera są obcinane.Trailing zeros are truncated. |
Specyfikacja szerokościWidth specification
W specyfikacji konwersji pole opcjonalnej specyfikacji szerokości pojawia się po każdym z flag znaków.In a conversion specification, the optional width specification field appears after any flags characters. Argument Width jest nieujemną liczbą całkowitą dziesiętną, która określa minimalną liczbę znaków, które są wyprowadzane.The width argument is a non-negative decimal integer that controls the minimum number of characters that are output. Jeśli liczba znaków w wartości wyjściowej jest mniejsza niż określona szerokość, puste wartości są dodawane do lewej lub prawej strony z wartościami — w zależności od tego, czy jest określona flaga wyrównania w lewo ( -
), aż do osiągnięcia minimalnej szerokości.If the number of characters in the output value is less than the specified width, blanks are added to the left or the right of the values—depending on whether the left-alignment flag ( -
) is specified—until the minimum width is reached. Jeśli Szerokość jest poprzedzona przez 0, zera wiodące są dodawane do liczby całkowitej lub konwersji zmiennoprzecinkowej do momentu osiągnięcia minimalnej szerokości, z wyjątkiem sytuacji, gdy konwersja jest nieskończona lub NaN.If width is prefixed by 0, leading zeros are added to integer or floating-point conversions until the minimum width is reached, except when conversion is to an infinity or NaN.
Specyfikacja szerokości nigdy nie powoduje obcięcia wartości.The width specification never causes a value to be truncated. Jeśli liczba znaków w wartości wyjściowej jest większa niż określona szerokość lub jeśli nie podano szerokości , wszystkie znaki wartości są wyprowadzane zgodnie ze specyfikacją precyzji .If the number of characters in the output value is greater than the specified width, or if width isn't provided, all characters of the value are output, subject to the precision specification.
Jeśli Specyfikacja szerokości jest gwiazdką ( *
), int
argument z listy argumentów dostarcza wartość.If the width specification is an asterisk (*
), an int
argument from the argument list supplies the value. Argument Width musi poprzedzać wartość, która jest formatowana na liście argumentów, jak pokazano w poniższym przykładzie:The width argument must precede the value that's being formatted in the argument list, as shown in this example:
printf("%0*d", 5, 3); /* 00003 is output */
Brakująca lub niewielka wartość szerokości w specyfikacji konwersji nie powoduje obcięcia wartości wyjściowej.A missing or small width value in a conversion specification doesn't cause the truncation of an output value. Jeśli wynik konwersji jest szerszy niż wartość szerokości , pole zostanie rozwinięte, aby zawierało wynik konwersji.If the result of a conversion is wider than the width value, the field expands to contain the conversion result.
Specyfikacja dokładnościPrecision specification
W specyfikacji konwersji trzecie pole opcjonalne jest specyfikacją precyzji.In a conversion specification, the third optional field is the precision specification. Składa się z kropki ( .
), po której następuje nieujemna liczba całkowita dziesiętna, która w zależności od typu konwersji określa liczbę znaków ciągu, liczbę miejsc dziesiętnych lub liczbę cyfr znaczących, które mają być wyprowadzane.It consists of a period (.
) followed by a non-negative decimal integer that, depending on the conversion type, specifies the number of string characters, the number of decimal places, or the number of significant digits to be output.
W przeciwieństwie do specyfikacji szerokości, Specyfikacja dokładności może spowodować Obcinanie wartości wyjściowej lub zaokrąglenie wartości zmiennoprzecinkowej.Unlike the width specification, the precision specification can cause either truncation of the output value or rounding of a floating-point value. Jeśli precyzja jest określona jako 0, a wartość do przekonwertowania to 0, wynik nie ma znaków wyjściowych, jak pokazano w tym przykładzie:If precision is specified as 0, and the value to be converted is 0, the result is no characters output, as shown in this example:
printf( "%.0d", 0 ); /* No characters output */
Jeśli Specyfikacja dokładności jest gwiazdką ( *
), int
argument z listy argumentów dostarcza wartość.If the precision specification is an asterisk (*
), an int
argument from the argument list supplies the value. Na liście argumentów argument dokładności musi poprzedzać wartość, która jest formatowana, jak pokazano w poniższym przykładzie:In the argument list, the precision argument must precede the value that's being formatted, as shown in this example:
printf( "%.*f", 3, 3.14159265 ); /* 3.142 output */
Znak typu określa interpretację dokładności lub precyzję domyślną, gdy precyzja zostanie pominięta, jak pokazano w poniższej tabeli.The type character determines either the interpretation of precision or the default precision when precision is omitted, as shown in the following table.
Jak wartości dokładności mają wpływ na typHow Precision Values Affect Type
TypType | ZnaczenieMeaning | DomyślneDefault |
---|---|---|
a , A a , A |
Precyzja określa liczbę cyfr po punkcie.The precision specifies the number of digits after the point. | Domyślna precyzja to 13.Default precision is 13. Jeśli precyzja to 0, nie jest drukowany punkt dziesiętny, chyba że # flaga jest używana.If precision is 0, no decimal point is printed unless the # flag is used. |
c , C c , C |
Precyzja nie ma żadnego wpływu.The precision has no effect. | Znak jest drukowany.Character is printed. |
d , i , o , u , x , X d , i , o , u , x , X |
Precyzja określa minimalną liczbę cyfr do wydrukowania.The precision specifies the minimum number of digits to be printed. Jeśli liczba cyfr w argumencie jest mniejsza niż precyzja , wartość wyjściowa zostanie uzupełniona o zero.If the number of digits in the argument is less than precision , the output value is padded on the left with zeros. Wartość nie jest obcinana, gdy liczba cyfr przekracza precyzję .The value isn't truncated when the number of digits exceeds precision . | Domyślna precyzja to 1.Default precision is 1. |
e , E e , E |
Precyzja określa liczbę cyfr do wydrukowania po przecinku dziesiętnym.The precision specifies the number of digits to be printed after the decimal point. Ostatnia wydrukowana cyfra jest zaokrąglana.The last printed digit is rounded. | Domyślna precyzja to 6.Default precision is 6. Jeśli precyzja to 0 lub kropka ( . ) pojawia się bez cyfry po niej, nie jest drukowany żaden punkt dziesiętny.If precision is 0 or the period (. ) appears without a number following it, no decimal point is printed. |
f , F f , F |
Wartość precyzji określa liczbę cyfr po przecinku dziesiętnym.The precision value specifies the number of digits after the decimal point. Jeśli zostanie wyświetlony punkt dziesiętny, przed nim zostanie wyświetlona co najmniej jedna cyfra.If a decimal point appears, at least one digit appears before it. Wartość jest zaokrąglana do odpowiedniej liczby cyfr.The value is rounded to the appropriate number of digits. | Domyślna precyzja to 6.Default precision is 6. Jeśli precyzja to 0, lub jeśli kropka ( . ) zostanie wyświetlona bez cyfry po niej, nie jest drukowany żaden punkt dziesiętny.If precision is 0, or if the period (. ) appears without a number following it, no decimal point is printed. |
g , G g , G |
Precyzja określa maksymalną liczbę cyfr znaczących.The precision specifies the maximum number of significant digits printed. | Drukowane są sześć cyfr znaczących, a końcowe zera są obcinane.Six significant digits are printed, and any trailing zeros are truncated. |
s , S s , S |
Precyzja określa maksymalną liczbę znaków do wydrukowania.The precision specifies the maximum number of characters to be printed. Nie są drukowane znaki o przekroczeniu precyzji .Characters in excess of precision aren't printed. | Znaki są drukowane, dopóki nie zostanie znaleziony znak o wartości null.Characters are printed until a null character is found. |
Specyfikacja rozmiaru argumentuArgument size specification
W specyfikacji konwersji pole size jest modyfikatorem długości argumentów dla specyfikatora konwersji typu .In a conversion specification, the size field is an argument length modifier for the type conversion specifier. Pola rozmiar prefiksy pola Typ —,,, hh
h
j
l
(małe litery L),,,,,,, L
ll
t
w
z
I
(wielkie i), I32
i I64
— określają "rozmiar" odpowiadającego argumentu — Long lub Short, 32-bitowy lub 64-bitowy, znak jednobajtowy lub szeroki, w zależności od specyfikatora konwersji, który modyfikuje.The size field prefixes to the type field— hh
, h
, j
, l
(lowercase L), L
, ll
, t
, w
, z
, I
(uppercase i), I32
, and I64
—specify the "size" of the corresponding argument—long or short, 32-bit or 64-bit, single-byte character or wide character—depending on the conversion specifier that they modify. Te prefiksy rozmiarów są używane z znakami typu w printf
i wprintf
rodzinach funkcji, aby określić interpretację rozmiarów argumentów, jak pokazano w poniższej tabeli.These size prefixes are used with type characters in the printf
and wprintf
families of functions to specify the interpretation of argument sizes, as shown in the following table. Pole size jest opcjonalne dla niektórych typów argumentów.The size field is optional for some argument types. Gdy nie określono prefiksu rozmiaru, program formatujący zużywa argumenty całkowite — na przykład, podpisane lub niepodpisane char
, short
,, int
long
i typy wyliczeniowe — jako 32-bitowe typy int
, i, float
double
i long double
argumenty zmiennoprzecinkowe są używane jako 64-bitowe double
typy.When no size prefix is specified, the formatter consumes integer arguments—for example, signed or unsigned char
, short
, int
, long
, and enumeration types—as 32-bit int
types, and float
, double
, and long double
floating-point arguments are consumed as 64-bit double
types. To zachowanie jest zgodne z domyślnymi regułami podwyższania poziomu argumentów dla list argumentów zmiennych.This behavior matches the default argument promotion rules for variable argument lists. Aby uzyskać więcej informacji na temat promocji argumentów, zobacz wielokropek i argumenty domyślne w wyrażeniach przyrostkowych.For more information about argument promotion, see Ellipsis and Default Arguments in Postfix expressions. W systemach 32-bitowych i 64-bitowych specyfikacja konwersji argumentu 64-bit Integer musi zawierać prefiks size ll
lub I64
.On both 32-bit and 64-bit systems, the conversion specification of a 64-bit integer argument must include a size prefix of ll
or I64
. W przeciwnym razie zachowanie programu formatującego nie jest zdefiniowane.Otherwise, the behavior of the formatter is undefined.
Niektóre typy mają różne rozmiary w 32-bitowym i 64-bitowym kodzie.Some types are different sizes in 32-bit and 64-bit code. Na przykład size_t
jest 32 bitów Long w kodzie skompilowanym dla x86 i 64 bitów w kodzie skompilowanym dla x64.For example, size_t
is 32 bits long in code compiled for x86, and 64 bits in code compiled for x64. Aby utworzyć kod formatowania niezależny od na platformie dla typów o zmiennej szerokości, można użyć modyfikatora rozmiaru argumentu o zmiennej szerokości.To create platform-agnostic formatting code for variable-width types, you can use a variable-width argument size modifier. Zamiast tego należy użyć modyfikatora rozmiaru argumentu 64-bitowego i jawnie podnieść typ argumentu o zmiennej szerokości do 64 bitów.Instead, use a 64-bit argument size modifier and explicitly promote the variable-width argument type to 64 bits. Modyfikator rozmiaru argumentu specyficzny dla firmy Microsoft I
obsługuje argumenty całkowite o zmiennej szerokości, ale zalecamy użycie j
modyfikatorów specyficznych dla typu t
i z
dla przenośności.The Microsoft-specific I
(uppercase i) argument size modifier handles variable-width integer arguments, but we recommend the type-specific j
, t
, and z
modifiers for portability.
Prefiksy rozmiarów dla specyfikatorów printf i wprintf Format-TypeSize Prefixes for printf and wprintf Format-Type Specifiers
Aby określićTo specify | Użyj prefiksuUse prefix | Ze specyfikatorem typuWith type specifier |
---|---|---|
char unsigned char |
hh |
d , i , o , u , x lub X d , i , o , u , x , or X |
short int short unsigned int |
h |
d , i , o , u , x lub X d , i , o , u , x , or X |
__int32 unsigned __int32 |
I32 |
d , i , o , u , x lub X d , i , o , u , x , or X |
__int64 unsigned __int64 |
I64 |
d , i , o , u , x lub X d , i , o , u , x , or X |
intmax_t uintmax_t |
j oraz I64 j or I64 |
d , i , o , u , x lub X d , i , o , u , x , or X |
long double |
l (mała litera L) lub L l (lowercase L) or L |
a , A ,,,,, e E f F g lub G a , A , e , E , f , F , g , or G |
long int long unsigned int |
l (mała litera L)l (lowercase L) |
d , i , o , u , x lub X d , i , o , u , x , or X |
long long int unsigned long long int |
ll (małe litery)ll (lowercase LL) |
d , i , o , u , x lub X d , i , o , u , x , or X |
ptrdiff_t |
t lub I (wielkie litery i)t or I (uppercase i) |
d , i , o , u , x lub X d , i , o , u , x , or X |
size_t |
z lub I (wielkie litery i)z or I (uppercase i) |
d , i , o , u , x lub X d , i , o , u , x , or X |
Znak jednobajtowySingle-byte character | h |
c oraz C c or C |
Znak dwubajtowyWide character | l (mała litera L) lub w l (lowercase L) or w |
c oraz C c or C |
Jednobajtowy ciąg znakówSingle-byte character string | h |
s , S lub Z s , S , or Z |
Ciąg znaków dwubajtowychWide-character string | l (mała litera L) lub w l (lowercase L) or w |
s , S lub Z s , S , or Z |
ptrdiff_t
Typy i size_t
są __int32
unsigned __int32
na platformach 32-bitowych i __int64
lub unsigned __int64
na platformach 64-bitowych.The ptrdiff_t
and size_t
types are __int32
or unsigned __int32
on 32-bit platforms, and __int64
or unsigned __int64
on 64-bit platforms. I
Prefiksy (wielką literą i),, j
t
i z
rozmiary, przyjmują poprawną szerokość argumentu dla danej platformy.The I
(uppercase i), j
, t
, and z
size prefixes take the correct argument width for the platform.
W Visual C++, chociaż long double
jest typem odrębnym, ma tę samą reprezentację wewnętrzną co double
.In Visual C++, although long double
is a distinct type, it has the same internal representation as double
.
hc
hC
Specyfikator typu or jest synonimem c
w printf
funkcjach Functions i with C
in wprintf
Functions.An hc
or hC
type specifier is synonymous with c
in printf
functions and with C
in wprintf
functions. lc
lC
wc
Specyfikator typu,,, lub wC
jest równoznaczny z C
w printf
funkcjach Functions i with c
in wprintf
Functions.A lc
, lC
, wc
, or wC
type specifier is synonymous with C
in printf
functions and with c
in wprintf
functions. hs
hS
Specyfikator typu or jest synonimem s
w printf
funkcjach Functions i with S
in wprintf
Functions.An hs
or hS
type specifier is synonymous with s
in printf
functions and with S
in wprintf
functions. ls
lS
ws
Specyfikator typu,,, lub wS
jest równoznaczny z S
w printf
funkcjach Functions i with s
in wprintf
Functions.An ls
, lS
, ws
, or wS
type specifier is synonymous with S
in printf
functions and with s
in wprintf
functions.
Uwaga
Specyficzne dla firmy Microsoft:Microsoft-specific:
I
Prefiksy modyfikatorów rozmiaru (Wielka litera i),, I32
I64
i w
argumentu są rozszerzeniami firmy Microsoft i nie są zgodne ze standardem ISO C.The I
(uppercase i), I32
, I64
, and w
argument size modifier prefixes are Microsoft extensions and are not ISO C-compatible. h
Prefiks, gdy jest używany z danymi typu char
i l
prefiksem (małymi literami L), gdy jest używany z danymi typu double
są rozszerzeniami firmy Microsoft.The h
prefix when it's used with data of type char
and the l
(lowercase L) prefix when it's used with data of type double
are Microsoft extensions.
Zobacz takżeSee also
printf, _printf_l, wprintf, _wprintf_l
printf_s, _printf_s_l, wprintf_s, _wprintf_s_l
printf_p
Parametry pozycyjneprintf_p
Positional Parameters