sscanf的安全版本sscanf_s的函数定义:
int sscanf_s( const char *buffer, const char *format [, argument ] ... );
在msdn中有如下mark,一定要仔细看哟,特别注意红色的部分,否则会出错的,我就在这里折腾了大半天才明白的
The sscanf_s function reads data from buffer into the location given by each argument. The arguments after the format string specify pointers to variables with a type that corresponds to a type specifier in format. Unlike the less secure version sscanf_s, a buffer size parametersizeOfBuffer is required when using the type field characters c, C, s, S and [. This parameter must be supplied as an additional parameter after each buffer which requires it.
也可以看下面这个例子的,注意红色的部分
// crt_sscanf_s.c
// This program uses sscanf_s to read data items
// from a string named tokenstring, then displays them.
#include <stdio.h>
int main( void )
{
char tokenstring[] = "15 12 14...";
char s[81];
char c;
int i;
float fp;
// Input various data from tokenstring:
// max 80 character string plus NULL terminator
sscanf_s( tokenstring, "%s", s, sizeof(s) );
sscanf_s( tokenstring, "%c", &c, sizeof(char) );
sscanf_s( tokenstring, "%d", &i );
sscanf_s( tokenstring, "%f", &fp );
// Output the data read
printf_s( "String = %s\n", s );
printf_s( "Character = %c\n", c );
printf_s( "Integer: = %d\n", i );
printf_s( "Real: = %f\n", fp );
}
Output
String = 15 Character = 1 Integer: = 15 Real: = 15.000000
fscanf_s,fwscanf_s用法和sscanf_s差不多,只是把字符串换成了打开的流。