scanf的官方解释:尽可能详细

本文引用了scanf的官方doc,指出了许多scanf使用过程中可能遇到的陷阱,足以解决大部分坑


man页面:

  1. White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input.
  2. Everything else matches only itself.
  3. 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依赖于缓冲区机制
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值