scanf_s 用法

今天,我在使用scanf_s编写C语言程序,因为是在visual stidio 2013 只能使用建立C++程序,再将后缀名改成.c来实现。
ANSI中的的scanf(),在读取时不检查边界,可能会造成内存访问越界,例如分配了5字节的空间但是读入了10字节 。
VS2013中也提供了scanf_s()。在调用时,必须提供一个数字以表明最多读取多少位字符,以便建立缓冲区接收输入信息,防止越界。这就要求程序在设计过程中就明确输入的长度。
形如:
scanf(“%c”, &cha);
scanf(“%s”, buf);<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span>
然而,并非是所有类型的输入都需要写出缓冲区长度。在使用过程中,我逐渐发现,整数和浮点数的输入不能写出缓冲区长度。其使用方式与scanf相同。
形如:
scanf(“%d”, &x);
scanf(“%f”, &exp);
scanf(“%lf”, &xpow);

    若后接数字,编译并不出错,但在运行过程中输入对应数据后将会出现错误。信息如下:
Unhandled exception at 0x1009E541 (msvcr120d.dll) in MyPro.exe: 
0xC0000005: Access violation writing location 0x00000008.

那么在连续输入不同类型的数据时,限定缓冲区大小的数字怎样排列呢?是的,紧跟在地址指针后面,中间用逗号相间隔。如果中间遇到整数、浮点数,则直接写下一个地址指针。(假设字符串大小为20)
形如:
scanf(“%s %c %d %s %f”, str1, 20, &cha1, 1, &integer1, str2, 20, &flo);

以下是MSDN中例子:
// crt_scanf_s.c
	// This program uses the scanf_s and wscanf_s functions
	// to read formatted input.
	#include <stdio.h>
	int main( void )
	{
	int i, result;
	float fp; char c, s[81];
	wchar_t wc, ws[81];
	result = scanf_s( "%d %f %c %C %s %S", &i, &fp, &c, 1, &wc, 1, s, 80, ws, 80 );
	printf( "The number of fields input is %d\n", result );
	printf( "The contents are: %d %f %c %C %s %S\n", i, fp, c, wc, s, ws);
	result = wscanf_s( L"%d %f %hc %lc %S %ls", &i, &fp, &c, 2, &wc, 1, s, 80, ws, 80 );
	wprintf( L"The number of fields input is %d\n", result );
	wprintf( L"The contents are: %d %f %C %c %hs %s\n", i, fp, c, wc, s, ws);
	return 0;
	}


版权声明:本文为sinat_26851263原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。