【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.
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:
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-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 by0x
or0X
.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-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 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 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.A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifierWhere 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.% 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:
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 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). 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 (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 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 函数的更多相关文章
- scanf printf函数返回值
1. scanf 函数是有返回值的,它的返回值可以分成三种情况 1) 正整数,表示正确输入参数的个数.例如执行 scanf("%d %d", &a, &b); ...
- scanf函数和printf函数
C程序实现输出和输入的 主要是printf函数 和 scanf函数,这两个函数是格式输入输出 格式声明由%和格式字符组成 如%d,%f 格式字符: d格式符:用来输出一个有符号的十进制整数 c格式 ...
- STM32 printf()函数和scanf()函数重定向到串口
STM32 printf()函数和scanf()函数重定向到串口 printf()函数和scanf()函数重定向 在学习STM32的时候,常常需要用串口来测试代码的正确与否,这时候就要要用到print ...
- scanf,printf函数细节
今天笔试的时候遇到一个考察C语言scanf函数的题目 int x; float y; scanf("%3d%f",&x,&y); // input 123456 6 ...
- C语言printf()函数:格式化输出函数
C语言printf()函数:格式化输出函数 头文件:#include <stdio.h> printf()函数是最常用的格式化输出函数,其原型为: int printf( char ...
- DSP:CCS V6 TMS320F2812 使用printf函数
使用Code Composer Studio Version: 6.1.1.00022,建立TMS320F2812工程. /* * main.c */ #include <stdio.h> ...
- 在keil中使用printf()函数的要点
在keil中printf默认是向串口中发送数据的,所以,如果应用该函数,必须先初始化串口,否则可能引起死机的情况,并且在printf之前应该先将TI置位,摘抄原因如下: 1.printf函数是调用pu ...
- 修改HAL标准库用printf函数发送数据直接输出
主函数文件,请直接关注自己写上去的代码: 直接看43行代码:#include "stdio.h"//要添加这个头文件 还有97行到112行:实现用HAL库函数和printf函数发送 ...
- 关于C语言中printf函数“输出歧视”的问题
目录 关于C语言中printf函数"输出歧视"的问题 问题描述 探索问题原因 另一种研究方法 问题结论 关于C语言中printf函数"输出歧视"的问题 问题描述 ...
随机推荐
- [Oracle]根据字段值全库搜索相关数据表和字段
这个需求比较冷门,但对于在某些特定的情况下,还是会有这样的需要的.好在Oracle实现还比较方便,用存储过程则轻松实现. 查询字符串: create or replace procedure sear ...
- 移动端meta viewport
<meta name="viewport" content=" width=device-width, user-scalable=no, initial-scal ...
- Struts详解
1.什么是MVC? MVC是Model,View,Controller的缩写,MVC是Application开发的设计模式, 也就是大家所知道的Model2.在MVC的设计模式中,它包括三类对象:(1 ...
- xutils3文件上传、下载、get、post请求
@ContentView(R.layout.activity_xutils3_net) public class XUtils3NetActivity extends Activity { @View ...
- Please install Android target
今天在执行ionic build android时出现以下错误: [Error: Please install Android target: "android-22". Hint ...
- mail
mail.php <?php require_once('class.phpmailer.php'); $mail = new PHPMailer(); //实例化 $mail->IsS ...
- ubuntu14.04 安装pip vitualenv flask
安装pip: $ apt-get install python-pip$ pip -V #查看版本 确认安装成功 安装完pip后,会发现下载的速度特别慢.按如下修改: $ vim ~/.pip/pip ...
- Python 3 并发编程多进程之进程同步(锁)
Python 3 并发编程多进程之进程同步(锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的,竞争带来的结果就是错乱,如何控制,就是加锁处理. 1. ...
- http keep-alive简解
http协议中,客户端发送请求,服务端在接收到请求后,返回所需要的数据后可以关闭连接,这样客户端读取完数据时会返回EOF(-1),表明数据已接受完全 备注:EOF end of file 什么是kee ...
- Mac OS下新建文本文档
---恢复内容开始--- 介绍 不知道小伙伴们有没有发现这样一件事情:Mac下没有新建文本文档!如果你恰好经常需要新建类似于.cpp,.in,.out等文件的话,每次终端用一堆$ cd命令再加上一句$ ...