|
发表于 2015-2-10 19:45:19
|
显示全部楼层
ANSI C中没有scanf_s(),只有scanf(),scanf()在读取时不检查边界,所以可能会造成内存访问越界。
result = scanf_s("%d %f ", &i, &fp); 的正确输入应该是:2空格4.0
scanf_s 的返回值是成功输入到变量的个数(上题是两个变量),第二题同理。
另外,scanf_s 输入含有字符,字符串,需要在后边追加一个参数限制缓冲区的长度,防止溢出。
请参考:
- // 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);
- }
复制代码 |
|