sscanf()----从一个字符串中读取与格式相符的数据,其实其作用相当于正则表示式,但没有正则表达式功能强大
函数原型:int sscanf( const char *buffer, const char *format [, argument ] ... );
buffer:储存的字符串
format:格式字符串
argument:选择性设定字符串
sscanf从buffer的数据然后按照argument进行写数据
头文件:#include <stdio.h>
sscanf与scanf相比,前者从固定字符串进行读取,后者从标准输入stdin中读取数据
第二个参数可以是一个或者多个:{%[*] [width] [{h | I | I64 | L}]type | ' ' | '\t' | '\n' | 非%符号},具体什么意思看看正则表达式就行了
例一:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char buf[512] ;
sscanf("123456", "%s", buf) ;
printf("%s\n", buf) ;
system("pause") ;
return 0 ;
}
输出:
例二:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char buf[512] ;
sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf);
printf("%s\n", buf);;
system("pause") ;
return 0 ;
}
输出:
例三:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
int a, b, c ;
sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c);
printf("%d, %d, %d\n", a, b, c);;
system("pause") ;
return 0 ;
}
输出:
注意这里的sscanf变量a,b,c前面需要加上&
例四:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char tokenstring[] = "15 12 14...";
char s[81];
char c;
int i;
float fp;
/* Input various data from tokenstring: */
sscanf( tokenstring, "%s", s );
sscanf( tokenstring, "%c", &c );
sscanf( tokenstring, "%d", &i );
sscanf( tokenstring, "%f", &fp );
/* Output the data read */
printf( "String = %s\n", s );
printf( "Character = %c\n", c );
printf( "Integer: = %d\n", i );
printf( "Real: = %f\n", fp );
system("pause") ;
return 0 ;
}
输出:
这是因为当其遇到数据中有空格时会结束