活用scanf

本文详细介绍了C语言中用于读取格式化数据的scanf()函数的工作原理及其丰富的格式化方式。通过解析scanf()的参数与格式化字符,读者可以深入了解如何正确使用此函数来读取各种格式的数据,包括整数、浮点数、字符和字符串等,并提供了实际编程示例加以说明。

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:
specifierDescriptionCharacters extracted
iIntegerAny 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 uDecimal integerAny number of decimal digits (0-9), optionally preceded by a sign (+ or -).
d is for a signed argument, and u for an unsigned.
oOctal integerAny number of octal digits (0-7), optionally preceded by a sign (+ or -).
Unsigned argument.
xHexadecimal integerAny number of hexadecimal digits (0-9a-fA-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -).
Unsigned argument.
fegFloating point numberA 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
cCharacterThe 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.
sString of charactersAny 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.
pPointer addressA 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]ScansetAny 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 scansetAny number of characters none of them specified as characters between the brackets.
nCountNo 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).
widthSpecifies the maximum number of characters to be read in the current reading operation (optional).
lengthOne 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
lengthd iu o xf e g ac s [] [^]pn
(none)int*unsigned int*float*char*void**int*
hhsigned char*unsigned char*   signed char*
hshort int*unsigned short int*   short int*
llong int*unsigned long int*double*wchar_t* long int*
lllong long int*unsigned long long int*   long long int*
jintmax_t*uintmax_t*   intmax_t*
zsize_t*size_t*   size_t*
tptrdiff_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=0;
	for(int i=0; s[i]; i++)
		for(int j=0; vow[j]; j++){
			if(s[i]==vow[j]){
				res++;
				break;
			}
		}
	return res;
}
int main(){
	//freopen("in", "r", stdin);
	char s[105];
	int ok[]={5, 7, 5};
	for(int i=0; i<3; i++){
		scanf(" %[^\n]", s);
		if(count_vow(s)!=ok[i]){
			puts("NO");
			return 0;
		}
	}
	puts("YES");
	return 0;
}

 

转载于:https://www.cnblogs.com/Patt/p/4700877.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值