sscanf()函数使用技巧
的有关信息介绍如下:scanf()函数,是标准输入输出库函数中的输入函数,它包含在头文件“stdio.h”中。作为与scanf()相似的函数sscanf()同样也包含在“stdio.h”中,灵活的使用库函数,将大大缩短程序的代码量。
函数原型:
int sscanf(const char *buffer,const char *format,[argument]...);
说明:sscanf()按照格式读取字符串中的数据,把数据传到字符串变量中。
the fuction is equivalent to fscanf except that the argument s specifies a strin from which the input is to be obtained, rather than from a stream.Reaching the end of the string is equivalent to encountering end-of-filefor the fscanf function. Returns: the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number ofinput items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
用法1:按长取
#include "stdio.h"int main(void){char str;sscanf("123456","%4s",str); printf("TEST 1: str = %s",str);}
说明:把"123456"字符串中,从左往右取4个,存到str中。
用法2:格式读
#include "stdio.h"int main(void){char str;int hour,minute,second; sscanf("14:55:34","%d:%d:%d",&hour,&minute,&second); printf("TEST 2: \r\n");printf("hour : %d\r\n", hour);printf("minute : %d\r\n", minute);printf("second : %d\r\n", second);}
说明:把14,55,34三个时间节点数据读取出来。
用法3:跳过
#include "stdio.h"int main(void){char str; sscanf("12345abc","%*d%s",str); printf("TEST 3: %s\r\n",str);}
说明:%*d 和 %*s 加了星号 (*) 表示跳过此数据不读入。实例中整型12345跳过。
用法4:取用有度
#include "stdio.h"int main(void){char str; sscanf("123+-+acc121","%[^a-z]",str);printf("TEST 4: %s\r\n",str);}
说明:如在上例中,取遇到小写字母为止的字符串。