scanf 返回值(你想知道的C语言 2.1)

Q: scanf的返回值和printf返回值一样吗?

A: scanf的返回值和printf返回值不一样, scanf对于输入多少字符并不敏感, 大多数情况下毫无意义. 但它对输入的变量个数很感兴趣.

    参考: printf 返回值 (你想知道的C语言 1.1)

These functions(scanf/fscanf...) return the number of input items assigned.

  只输入一个变量:

/*
   Xi Chen(511272827@qq.com)
   cxsjabcabc
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int n, ret;

	ret = scanf("%d", &n);
	printf("n:%d, ret:%d\n", n, ret);

	return 0;
}

  输入128或者128 abc, 都会输出:  "n:128, ret:1".

 

Q:  除此之外, scanf返回值的意义还在哪里?

A: 当有多个输入变量, 我们可能没办法对于每个变量都判断是否成功输入, 以最终成功输入的个数更简单方便.

/*
   Xi Chen(511272827@qq.com)
   cxsjabcabc
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int ret;
	int a, b;

	ret = scanf("%d %d", &a, &b);
	printf("a:%d, b:%d, ret:%d\n", a, b, ret);

	return 0;
}

   

   

  当输入1 a 2, 变量b没有成功输入, 最终返回1.

  我们可以利用返回值提前得知输入是否满足预期.

  https://github.com/cxsjabc/basic/blob/dev/c/_topics/scanf/scanf_two_arg1.c

/*
   Xi Chen(511272827@qq.com)
   cxsjabcabc
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int ret;
	int a, b;

	if ((ret = scanf("%d %d", &a, &b)) == 2) 
		printf("a:%d, b:%d, ret:%d\n", a, b, ret);
	else
		printf("scanf error:%d\n", ret);

	return 0;
}

  输出如下:

   

  同样, fscanf, sscanf, vscanf, vsscanf, vfscanf的返回值和scanf类似.

 

  kernel scanf

    kernel对于参数判断更严格, 以免有漏洞, 同样也有类似实现通过返回值判断用户空间参数是否符合预期.

     例如, Linux power.c:

      

 

   Mac Libc源代码scanf返回值

     https://opensource.apple.com/source/Libc/Libc-1272.250.1/stdio/FreeBSD/vfscanf.c.auto.html

      nassigned变量保存输入成功的变量, 每次成功nassigned++;

      程序返回:  return (nassigned);     

      例如, 处理输入浮点数:

          

 

作者:     陈曦
环境:     MacOS 10.14.5
         Apple LLVM version 10.0.1 (clang-1001.0.46.4)
         Target: x86_64-apple-darwin18.6.0
 
转载请注明出处

 

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值