本文引用了scanf的官方doc,指出了许多scanf使用过程中可能遇到的陷阱,足以解决大部分坑
man页面:
- White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input.
- Everything else matches only itself.
- Scanning stops when an input character does not match such a format character. Scanning also stops when an input conversion cannot be made
关于空白字符
空白字符可以不被match到
int d;
char s[100];
scanf("%d %s", &d, s);
输入123abc
, 得d=123
, s="abc"
空白字符可以被match多次
int d;
scanf("%d\n", &d); //把`\n`换成` `, `\t`, 实验结果不变
printf("d=%d",d);
输入123回车回车空格回车
…
不管输入多少个空白字符,scanf都不会停止,直到遇到非空白字符.
关于格式控制串
most match skip white space; This white space is not counted against the field width.
也就是说前导空白字符一般会被忽略,哪怕是用了比如%3d
这样的字眼。
scanf中的%d
[+-]数字
scanf中的%f
我只想考虑10进制的,完整的doc请看man页面.
[+-]数字[.]数字[E[+-]数字]
scanf中的%s
Matches a sequence of non-white-space characters; The input string stops at white space or at the maximum field width, whichever occurs first.
别忘了在正则里面\S
是非空白字符的意思
scanf中的%c
Matches a sequence of width count characters (default 1);
The usual skip of leading white space is suppressed.
To skip white space first, use an explicit space in the format.
缓冲区机制使得多句scanf语句等价于一条scanf
例如这个:
#include <stdio.h>
int main(){
int a;
char c;
scanf("%d",&a);
scanf("%c",&c);
printf("%d %c",a,c);
}
在上面的程序中:
- 输入
123回车
, a=123, c=回车 - 输入
123 X回车
, a=123, c=空格, 末尾的X被丢弃 - 输入
123X回车
, a=123, c=X
可见完全等价于scanf("%d%c", &a,&c);
这是因为scanf
依赖于缓冲区机制