sscanf()函数

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 ;
}

输出:

这是因为当其遇到数据中有空格时会结束





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值