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

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

specifier Description Characters 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-specifier description
* 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
length d i u o x f e g a c s [] [^] p n
(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:

specifier Output Example
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:

flags description
- 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).
width description
(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.
.precision description
.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
length d i u o x X f F e E g G a A c s p n
(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"。

时间: 2024-10-17 00:07:12

【C/C++】scanf,printf 函数的相关文章

黑马程序员----printf函数和scanf函数

一.printf函数和scanf函数,都被定义在头文件stdio.h里,因此在使用scanf函数时要加上#include <stdio.h>. 二.printf函数 1.定义:printf()函数是格式化输出函数, 一般用于向终端按规定格式输出信息; 2.格式:printf("XXXXXXXX"); 三.scanf函数 1.定义:scanf()函数按用户指定的格式从键盘上把数据输入到指定的变量之中; 2.格式:scanf("%d", &numbe

scanf,printf函数细节

今天笔试的时候遇到一个考察C语言scanf函数的题目 int x; float y; scanf("%3d%f",&x,&y); // input 123456 678 enter and then what's the value of x and y printf("%d %f",x,y); 程序的执行结果是: 123 456.0000000 看来还是自己对scanf函数不是很了解,现在看看scanf函数的描述如下: 格式:既字符串序列,它控制从

scanf,printf函数的返回值

参考自:https://www.douban.com/note/220299804/ scanf函数的返回值有三种情况: (1)第一种就是返回一个正整数,表示输入成功元素的个数. (2)第二种如果返回的值为0,代表输入不匹配,没有正确输入任何值,所以有了下面的代码. (3)第三种返回-1(EOF)也就是输入流结束.Windows:CTRL + Z表示输入结束,Linux:CTRL + D. printf函数的返回值为输出元素的个数.printf("%d\n", 1);  //2 #in

scanf函数和printf函数

C程序实现输出和输入的 主要是printf函数 和 scanf函数,这两个函数是格式输入输出 格式声明由%和格式字符组成 如%d,%f 格式字符:  d格式符:用来输出一个有符号的十进制整数  c格式符:用来输出一个字符  s格式符:用来输出一个字符串 f格式符:用来输出实数(包括单精度,双精度,长双精度) 隐含输出六位小数  e格式符:用格式声明%e指定以指数形式输出实数  i格式符:作用与d格式符相同,一般习惯用%d,而少用%i.  o格式符:以八进制的形式输出  u格式符:用来输出无符号(

学C第5天(printf函数,scanf函数)

一.格式 1.%d格式 %[-]d      左对齐     %[m]d      以m指定的字段宽度输出,数据的位数小于m,左端补空格     %[0m]d     以m指定的字段宽度输出,数据的位数小于m,则左端补0     %[l]d    输出长整型整数     %[-m]d  左对齐,忽视0或空格 int num = 1000;     printf("%-d", num);//1000     printf("\n%10d", num); //     

scanf和printf函数的返回值

<span style="font-size:24px;color:#000099;"> scanf函数返回的是输入值的个数 而printf函数则是返回打印字符的个数 特别注意的是 \t 也只是表示的是一个字符<img src="http://img.blog.csdn.net/20150422143816136?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhvdTc1MzA5OTk0Mw==/font/5a

scanf函数与printf函数用法

一开始学习就是用的cin.cout,所有习惯用这个,但是后来做题发现这样的输入方式有弊端,所以决定整理熟悉一下scanf函数与printf函数. 头文件 # include <stdio.h> scanf("输入控制符",输入参数) 在 scanf 的“输入参数”中,变量前面的取地址符&不要忘记. scanf 中双引号内,除了“输入控制符”外什么都不要写. “输出控制符”和“输出参数”无论在“顺序上”还是在“个数上”一定要一一对应. “输入控制符”的类型和变量所定义

C 的printf函数

头文件 #include <stdio.h> printf函数是最常用的格式化输出函数,原型为:int printf(char *format,......); printf函数会根据参数format字符串来转换并格式化数据,然后输出 参数format字符串可包含下列三种字符类型: 一般文本,将直接输出 ASCII控制字符,即转义符 格式转换字符 格式转换字符为一个百分比符号(%)及其后的格式字符所组成.每个%符号在其后都必须有一个参数与之相呼应 整数: %d 会被转换为有符号的十进制数字 %

linux中fflush函数和printf函数 【转】

本文转载自:http://blog.chinaunix.net/uid-30058258-id-5029847.html printf是一个行缓冲函数printf函数是标准函数,最终会调用到系统调用函数,printf函数会掉用到write系统函数:但是调用write函数需要满足一些条件件.(1)缓冲区满(2)遇到\n \r(3)调用fflush函数来冲洗缓冲区(4)scanf读取缓冲区的内容(5)调用printf函数的进程或线程结束会调用fflush函数检测缓冲区的大小为1024B.fflush