码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-09-22 23:54:54      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:www.   bsp   stdin   tput   mat   count   floating   说明   arch   

摘自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.

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-9a-fA-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -).
Unsigned argument.
feg 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.
% % % 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 hhhllljztL (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.

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.
 
% % followed by another % character will write a single % to the stream. %

The format specifier can also contain sub-specifiers: flagswidth.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 ox or X specifiers the value is preceeded with 00x or 0X respectively for values different than zero.
Used with aAeEfFg 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 (diouxX): 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 aAeEf 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 precision0 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 函数

标签:www.   bsp   stdin   tput   mat   count   floating   说明   arch   

原文地址:http://www.cnblogs.com/Atanisi/p/7525951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!