sscanf,sscanf_s及其相关用法[转]

发布时间 2023-04-10 14:23:56作者: 3D入魔

#include<stdio.h>

 定义函数 int sscanf (const char *str,const char * format,........);

函数说明 
 sscanf()会将参数str的字符串根据参数format字符串来转换并格式化数据。格式转换形式请参考scanf()。转换后的结果存于对应的参数内。

返回值 成功则返回参数数目,失败则返回-1,错误原因存于errno中。 返回0表示失败    否则,表示正确格式化数据的个数    例如:sscanf(str,"%d%d%s", &i,&i2, &s);    如果三个变成都读入成功会返回3。    如果只读入了第一个整数到i则会返回1。证明无法从str读入第二个整数。

 int i; 
 unsigned int j; 
 char input[ ]=”10 0x1b aaaaaaaa bbbbbbbb”; 
 char s[5]; 
 sscanf(input,”%d %x %5[a-z] %*s %f”,&i,&j,s,s); 
 printf(“%d %d %s ”,i,j,s); 

警告内容:
 warning C4996: 'sscanf': This function or variable may be unsafe. Consider using sscanf_s instead. 
 
据了解,“_s”版本函数是微软后来对c++做得扩展,用来替代原先不安全的函数,例如:printf、scanf、strcpy、fopen等等。

详细参考:
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_vccrt/html/d9568b08-9514-49cd-b3dc-2454ded195a3.htm

原来安全版本的函数,对参数和缓冲边界做了检查,增加了返回值和抛出异常。这样增加了函数的安全性,减少了出错的几率

char str[100];
    //用法一:取指定长度的字符串    注意后面要加大小
    sscanf_s("12345", "%4s", str, sizeof(str));
    printf("用法一\nstr = %s\n", str);
 
    //用法二:格式化时间  
    int year, month, day, hour, minute, second;
    sscanf_s("2013/02/13 14:55:34", "%d/%d/%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
    printf("用法二\ntime = %d-%d-%d %d:%d:%d\n", year, month, day, hour, minute, second);
 
    //用法三:读入字符串  
    sscanf_s("12345", "%s", str,sizeof(str));
    printf("用法三\nstr = %s\n", str);
 
    //用法四:%*d 和 %*s 加了星号 (*) 表示跳过此数据不读入. (也就是不把此数据读入参数中)  
    sscanf_s("12345acc", "%*d%s", str, sizeof(str));
    printf("用法四\nstr = %s\n", str);
 
    //用法五:取到指定字符为止的字符串。如在下例中,取遇到'+'为止字符串。  
    sscanf_s("12345+acc", "%[^+]", str, sizeof(str));
    printf("用法五\nstr = %s\n", str);
 
    //用法六:取到指定字符集为止的字符串。如在下例中,取遇到小写字母为止的字符串。  
    sscanf_s("12345+acc121", "%[^a-z]", str, sizeof(str));
    printf("用法六\nstr = %s\n", str);
 
    //综合测试
    char str1[100] = "123568qwerSDDAE";
    char lowercase[100];
    int num;
    sscanf_s(str1, "%dq%[a-z]", &num, lowercase,sizeof(str1));
    printf("The number is: %d.\n", num);
    printf("The lowercase is: %s.", lowercase);