天天看点

scanf 格式和输入不匹配(你想知道的C语言 2.4)

 printf章节, 我们有提到格式符和参数不匹配, scanf同样存在类似的问题, 分析此类问题的最佳途径依然是libc源代码和汇编.

    printf 格式串和参数不匹配的后果(你想知道的C语言 1.10)

Q: scanf("%d", &n); 输入1.5, n是多少?

A: 1.5被当做浮点数? 当然不是, scanf对于所有输入都当做字符, 在如上场景, 接收到小数点时, 就终止了!  所以n是1.

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

       Line: 671 ~ 759 对于整形, 遇到0~9或十六进制符号ABCDEFX有效, 否则会退出解析!

scanf 格式和输入不匹配(你想知道的C语言 2.4)

Q: 由上, 想到一个问题: 当n是int类型, scanf("%d", n);  n是什么数值才不会挂掉?

A:  64位系统, 改用long类型. n设置为另外一个long变量的地址, 就可以保证不会挂掉.

/*
   Xi Chen([email protected])
   cxsjabcabc
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

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

	n = (long)&a;
	scanf("%ld", n);
	
	printf("%ld\n", a);

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