scanf()是C语言中用于读入格式化数据(formatted data)的函数。

我们可能对scanf()的一般用法已经了然,而至于scanf()读入数据的机制恐怕并不十分清楚。

下面我将比较详细地介绍scanf()的工作机制,并指出其丰富且强大的格式化方式。

内容来自这个链接

Function

int scanf ( const char * format, ... );
Read formatted data from stdin 
(务必注意 formatted data这两个词)

Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.
The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.

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).
  • 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 0xhexadecimal 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 lengthsub-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).

用法举例 1

Codeforces 78A

题目大意:

从stdin读入3行由小写英文字母 (lowercase Latin letters) 与空格 (space) 组成的字符串,统计每行中元音字母 (a, e, i, o, u)出现的次数,看是否依次为5, 7, 5。

问题归结为如何读入包含空格的一整行,根据上述题目中的要求我们将问题具体描述为:

如何读入含有空格的一整行字符串,起始空格(leading spaces)可忽略。

#include<bits/stdc++.h>
using namespace std;
const char *vow="aeiou";
int count_vow(char *s){
int res=;
for(int i=; s[i]; i++)
for(int j=; vow[j]; j++){
if(s[i]==vow[j]){
res++;
break;
}
}
return res;
}
int main(){
//freopen("in", "r", stdin);
char s[];
int ok[]={, , };
for(int i=; i<; i++){
scanf(" %[^\n]", s);
if(count_vow(s)!=ok[i]){
puts("NO");
return ;
}
}
puts("YES");
return ;
}

活用scanf的更多相关文章

  1. 人活着系列之平方数 分类: sdutOJ 2015-06-22 17:10 7人阅读 评论(0) 收藏

    人活着系列之平方数 Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^ 题目描述 偶然和必然?命运与意志?生与死?理性与情感?价值与非价值?在&quo ...

  2. 人活系列Streetlights (秩)

    人活着系列之Streetlights Time Limit: 1000MS Memory limit: 65536K 题目描写叙述 人活着假设是为了家庭,亲情----能够说是在这个世界上最温暖人心的, ...

  3. zzulioj--1613--少活一年?(稍微有点坑,水!)

    1613: 少活一年? Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 344  Solved: 70 SubmitStatusWeb Board De ...

  4. 人活着系列Tanya和蔡健雅猪 (floyd)

    人活着系列之芳姐和芳姐的猪 Time Limit: 1000MS Memory limit: 65536K 题目描写叙述 芳姐特别喜欢猪,所以,她特意养了m个猪圈,顺便在k条无向边,每条边有都有起点v ...

  5. C语言实现计算“已经活了多少天”

    输入生日,通过系统或者自己输入,获得当前日期,计算已经存活了多少天. #include<stdio.h> #include<time.h> /** * 函数介绍: * 通过输入 ...

  6. scanf()中清除输入缓冲区的几种方法归纳

    应用场景:我们使用多个scanf()的时候,如果输入缓冲区还有数据的话,那么scanf()就不会询问用户输入,而是直接就将输入缓冲区的内容拿出来用了,这就导致了前面的错误影响到后面的内容,为了隔离这种 ...

  7. VS2015使用scanf报错的解决方案

    1.在程序最前面加: #define _CRT_SECURE_NO_DEPRECATE 2.在程序最前面加: #pragma warning(disable:4996) 3.把scanf改为scanf ...

  8. scanf类型不匹配造成死循环

        int i = 0; while (flag) { printf("please input a number >>> "); scanf("% ...

  9. C语言: 运算符,printf,scanf的用法

    运算符/的运算结果和运算对象的数据类型有关,两个数都是in,则商就是int,取整数部分:被除数和除数中只要有一个或两个都是浮点型数据,则商也是浮点型,不去掉小数部分如:16/5 == 3:16/5.0 ...

随机推荐

  1. 【转】【C#】C# 垃圾回收机制

    摘要:今天我们漫谈C#中的垃圾回收机制,本文将从垃圾回收机制的原理讲起,希望对大家有所帮助. GC的前世与今生 虽然本文是以.NET作为目标来讲述GC,但是GC的概念并非才诞生不久.早在1958年,由 ...

  2. C++ STL之vector详解

    转自http://blog.sina.com.cn/s/blog_9f1c0931010180cy.html Vectors   vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作 ...

  3. XPath 详解,总结

    XPath简介 XPath是W3C的一个标准.它最主要的目的是为了在XML1.0或XML1.1文档节点树中定位节点所设计.目前有XPath1.0和XPath2.0两个版本.其中Xpath1.0是199 ...

  4. Eclipse系列: 在Eclipse中用TODO标签管理任务(Task)(ZZ)

    Elipse为Java项目的时候,有一个很人性化的"任务管理"功能,利用这个功能可以方便地将项目中一些需要处理的任务记录下来.先来看看"任务管理"是怎么使用的吧 ...

  5. [CareerCup] 1.6 Rotate Image 翻转图像

    1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a m ...

  6. Linux第十一次学习笔记

    异常控制流 异常控制流(ECF)发生在计算机系统的各个层次 在硬件层,硬件检测到的事件会触发控制突然转移到异常处理程序. 在操作系统层,内核通过上下文转换将控制从一个用户进程转移到另一个用户进程. 在 ...

  7. Linux下高频命令分类辑录(基本使用篇)

    本文目的:总结linux下常用命令的基本使用方法 文件权限: 文档权限设置命令:chmod 数字模式: 文档权限由-rwxrwxrwx十个字符组成,其中第一个代表文档类型,后面九个字符按照顺序分为三组 ...

  8. 微信小程序开发常见问题分析

    距离微信小程序内测版发布已经有十几天的时间了,网上对微信小程序的讨论也异常火爆,从发布到现在微信小程序一直占领着各种技术论坛的头条,当然各种平台也对微信小程序有新闻报道,毕竟腾讯在国内影响力还是很大的 ...

  9. Dictionary使用

    /// <summary> /// 除去数组中的空值和签名参数并以字母a到z的顺序排序 /// </summary> /// <param name="dicA ...

  10. Matrix67大牛推荐的省选知识点

    时间复杂度(渐近时间复杂度的严格定义,NP问题,时间复杂度的分析方法,主定理)排序算法(平方排序算法的应用,Shell排序,快速排序,归并排序,时间复杂度下界,三种线性时间排序,外部排序)数论(整除, ...