1. 程式人生 > >【C/C++】scanf,printf 函數

【C/C++】scanf,printf 函數

mini tis sig could mantis body take n) 緩沖區

摘自http://www.cplusplus.com

1. scanf 函數

int scanf ( const char * format, ... );

Parameters

format

C string that contains a sequence of characters that control how characters extracted from the stream are treated:
  • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format
    string validates any quantity of whitespace characters extracted from the stream (including none).(空白字符包括 ‘ ‘空格, ‘\t‘ 水平制表符, ‘\n‘換行符, ‘\v‘縱向制表符, ‘\f‘走紙符, ‘\r‘回車五種,另外 回車 r 本義是光標重新回到本行開頭,r的英文return,控制字符可以寫成CR,即Carriage Return,對應ASCII碼為十六進制的0x0D,十進制的13;換行 n 本義是光標往下一行(不一定到下一行行首,即當前光標在什麽位置,就換到下一行的那個位置),n的英文newline,控制字符可以寫成LF,即Line Feed,對應ASCII碼為十六進制的0x0A,十進制的10。一般的ENTER鍵:在windows系統下 = r + n;
    在Unix類系統(Linux,…)下 = n; 在Mac系統下 = r)
  • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format
    . If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
  • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments.

A format specifier for scanf follows this prototype:

%[*][width][length]specifier

Where the specifier character at the end is the most significant component, since it defines which characters are extracted, their interpretation and the type of its corresponding argument:
specifierDescriptionCharacters extracted
i Integer Any number of digits, optionally preceded by a sign (+ or -).
Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f).
Signed argument.
d or u Decimal integer Any number of decimal digits (0-9), optionally preceded by a sign (+ or -).
d is for a signed argument, and u for an unsigned.
o Octal integer Any number of octal digits (0-7), optionally preceded by a sign (+ or -).
Unsigned argument.
x Hexadecimal integer Any number of hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -).
Unsigned argument.
f, e, g Floating point number A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod).
Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
a
c Character The next character. If a width other than 1 is specified, the function reads exactly width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
s String of characters Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
p Pointer address A sequence of characters representing a pointer. The particular format used depends on the system and library implementation, but it is the same as the one used to format %p in fprintf.
[characters] Scanset Any number of the characters specified between the brackets.
A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters] Negated scanset Any number of characters none of them specified as characters between the brackets.
n Count No input is consumed.
The number of characters read so far from stdin is stored in the pointed location.
% % A % followed by another % matches a single %.
Except for n, at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.

The format specifier can also contain sub-specifiers: asterisk (*), width and length (in that order), which are optional and follow these specifications:
sub-specifierdescription
* An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).
width Specifies the maximum number of characters to be read in the current reading operation (optional).
length One of hh, h, l, ll, j, z, t, L (optional).
This alters the expected type of the storage pointed by the corresponding argument (see below).

This is a chart showing the types expected for the corresponding arguments where input is stored (both with and without a length sub-specifier):
specifiers
lengthd iu o xf e g ac s [] [^]pn
(none) int* unsigned int* float* char* void** int*
hh signed char* unsigned char* signed char*
h short int* unsigned short int* short int*
l long int* unsigned long int* double* wchar_t* long int*
ll long long int* unsigned long long int* long long int*
j intmax_t* uintmax_t* intmax_t*
z size_t* size_t* size_t*
t ptrdiff_t* ptrdiff_t* ptrdiff_t*
L long double*
Note: Yellow rows indicate specifiers and sub-specifiers introduced by C99.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type.
There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.
These arguments are expected to be pointers: to store the result of a scanf operation on a regular variable, its name should be preceded by the reference operator (&) (see example).

Return Value

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.

2. printf 函數

int printf ( const char * format, ... );

Parameters

format
C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.

A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier

Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifierOutputExample
d or i Signed decimal integer 392
u Unsigned decimal integer 7235
o Unsigned octal 610
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (uppercase) 7FA
f Decimal floating point, lowercase 392.65
F Decimal floating point, uppercase 392.65
e Scientific notation (mantissa/exponent), lowercase 3.9265e+2
E Scientific notation (mantissa/exponent), uppercase 3.9265E+2
g Use the shortest representation: %e or %f 392.65
G Use the shortest representation: %E or %F 392.65
a Hexadecimal floating point, lowercase -0xc.90fep-2
A Hexadecimal floating point, uppercase -0XC.90FEP-2
c Character a
s String of characters sample
p Pointer address b8000000
n Nothing printed.
The corresponding argument must be a pointer to a signed int.
The number of characters written so far is stored in the pointed location.
% A % followed by another % character will write a single % to the stream. %

The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:

flagsdescription
- Left-justify within the given field width; Right justification is the default (see width sub-specifier). 左對齊
+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign. 右對齊
(space) If no sign is going to be written, a blank space is inserted before the value. 輸出值為正時冠以空格,為負時冠以負號
# Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero.
Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written. 對o類,在輸出時加前綴o;對x/X類,在輸出時加前綴0x/0X;對e、g、f 類當結果有小數時才給出小數點。
0 Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).

widthdescription
(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. 若實際位數多於定義的寬度,則按實際位數輸出,若實際位數少於定義的寬度則補以空格或0。
* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precisiondescription
.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.

如果輸出數字,則表示小數的位數;如果輸出的是字符,則表示輸出字符的個數;若實際位數大於所定義的精度數,則截去超過的部分。

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

The length sub-specifier modifies the length of the data type. This is a chart showing the types used to interpret the corresponding arguments with and without length specifier (if a different type is used, the proper type promotion or conversion is performed, if allowed):
specifiers
lengthd iu o x Xf F e E g G a Acspn
(none) int unsigned int double int char* void* int*
hh signed char unsigned char signed char*
h short int unsigned short int short int*
l long int unsigned long int wint_t wchar_t* long int*
ll long long int unsigned long long int long long int*
j intmax_t uintmax_t intmax_t*
z size_t size_t size_t*
t ptrdiff_t ptrdiff_t ptrdiff_t*
L long double
Note regarding the c specifier: it takes an int (or wint_t) as argument, but performs the proper conversion to a char value (or a wchar_t) before formatting it for output.

Note: Yellow rows indicate specifiers and sub-specifiers introduced by C99. See <cinttypes> for the specifiers for extended types.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Return Value

On success, the total number of characters written is returned.

If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.

If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.

3. 使用總結:

  1.如果想顯示數值的前綴,可以使用說明符 ’%#n‘, ‘%#x‘, ‘%#X‘分別生成 ‘0’, ‘0x‘, ‘0X‘ 前綴。

  2.對於scanf函數,需求%s類型時,“\n”是不會影響scanf內容的,對於需求%c類型時,\n也是字符,自然會有影響. 參考博文scanf函數和回車、空格 及其返回值

    scanf函數的結束通常有3種,所謂的whitespace:遇到空格、回車或者tab鍵;或者按照格式控制符的指定來控制結束,如%5d類的格式;遇到非法輸入也會自動結束。

    對常用的三種格式,結束符號分別如下:

  %d格式,默認分隔符是所有的 white-spaces(空格、回車、制表);

  %c格式,則按ASCII字符考慮,無分隔符。可能會受到之前輸入的影響,必要時用fflush(stdin);清除緩沖區,就是說whitespace也會被scanf讀進;

  %s格式,默認分隔符是所有的 white-spaces,輸入後自動加入結束符"\0"。

【C/C++】scanf,printf 函數