摘自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"。

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

  1. scanf printf函数返回值

    1. scanf 函数是有返回值的,它的返回值可以分成三种情况  1) 正整数,表示正确输入参数的个数.例如执行 scanf("%d %d", &a, &b);   ...

  2. scanf函数和printf函数

    C程序实现输出和输入的 主要是printf函数 和 scanf函数,这两个函数是格式输入输出 格式声明由%和格式字符组成 如%d,%f 格式字符:  d格式符:用来输出一个有符号的十进制整数  c格式 ...

  3. STM32 printf()函数和scanf()函数重定向到串口

    STM32 printf()函数和scanf()函数重定向到串口 printf()函数和scanf()函数重定向 在学习STM32的时候,常常需要用串口来测试代码的正确与否,这时候就要要用到print ...

  4. scanf,printf函数细节

    今天笔试的时候遇到一个考察C语言scanf函数的题目 int x; float y; scanf("%3d%f",&x,&y); // input 123456 6 ...

  5. C语言printf()函数:格式化输出函数

    C语言printf()函数:格式化输出函数 头文件:#include <stdio.h> printf()函数是最常用的格式化输出函数,其原型为:     int printf( char ...

  6. DSP:CCS V6 TMS320F2812 使用printf函数

    使用Code Composer Studio  Version: 6.1.1.00022,建立TMS320F2812工程. /* * main.c */ #include <stdio.h> ...

  7. 在keil中使用printf()函数的要点

    在keil中printf默认是向串口中发送数据的,所以,如果应用该函数,必须先初始化串口,否则可能引起死机的情况,并且在printf之前应该先将TI置位,摘抄原因如下: 1.printf函数是调用pu ...

  8. 修改HAL标准库用printf函数发送数据直接输出

    主函数文件,请直接关注自己写上去的代码: 直接看43行代码:#include "stdio.h"//要添加这个头文件 还有97行到112行:实现用HAL库函数和printf函数发送 ...

  9. 关于C语言中printf函数“输出歧视”的问题

    目录 关于C语言中printf函数"输出歧视"的问题 问题描述 探索问题原因 另一种研究方法 问题结论 关于C语言中printf函数"输出歧视"的问题 问题描述 ...

随机推荐

  1. P1009 阶乘之和

    P1009 阶乘之和 题目提供者洛谷OnlineJudge 标签数论(数学相关)高精1998NOIp提高组NOIp普及组 难度普及- 通过/提交1139/3791 提交该题 讨论 题解 记录 题目描述 ...

  2. plsql 详细安装及汉化步骤

    方法/步骤   双击运行plsqldev715 安装完成后我们装中文补丁: 双击运行‘Chinese’应用程序 找到PLSQL的安装目录添加进来 中文补丁安装完成后我们需要进行orcl的配置,配置好才 ...

  3. 启动/关闭Spring boot服务脚本

    启动Spring boot服务脚本 #!/bin/bash cd /test java -jar test.jar &> ./test.log & echo "成功&q ...

  4. Django自定义对象转成json字符串

    1.定义转换函数:def convert_to_builtin_type(obj): print 'default(', repr(obj), ')' # 把MyObj对象转换成dict类型的对象 d ...

  5. python+NLTK 自然语言学习处理八:分类文本一

    从这一章开始将进入到关键部分:模式识别.这一章主要解决下面几个问题 1 怎样才能识别出语言数据中明显用于分类的特性 2 怎样才能构建用于自动执行语言处理任务的语言模型 3 从这些模型中我们可以学到那些 ...

  6. Cordova 教程 学习步骤-从零基础开始

    Cordova的技术交流新群

  7. (转)基于libRTMP的流媒体直播之 AAC、H264 推送

    参考: 1,基于libRTMP的流媒体直播之 AAC.H264 推送 http://billhoo.blog.51cto.com/2337751/1557646

  8. virtualbox 桥接 (转)

    virtualbox 自带的网络配置模式要么选择host-only,要么bridge,对于经常使用virtualbox的同学一定想要像vmware一样的nat配置,既可以让host访问guest,又可 ...

  9. [原创]java WEB学习笔记42:带标签体的自定义标签,带父标签的自定义标签,el中自定义函数,自定义标签的小结

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  10. hd acm1008

    Problem Description The highest building in our city has only one elevator. A request list is made u ...