sscanf的用法

///
 /// @file    test6.cc
 /// @author  Mrxu
 /// @date    2018-12-28 11:08:45
 ///
 
#include<stdio.h> 
#include<string.h>
#include <iostream>
#include<string>

using std::cout;
using std::endl;
using std::string;

int main()
{
	char str[20] = {0};
	char tmp1[20] = {0};
	char tmp2[20] = {0};
	char tmp3[20] = {0};
	int digit;

	/*格式化输出到数组中*/
	sprintf(str,"%s %d %s","hello",123,"world");

	/*1.读取到相应类型变量中*/
	sscanf(str,"%s%d%s",tmp1,&digit,tmp2);
	
	/*可以不用空格隔开
	sprintf(str,"%s%d%s","hello",123,"world");
	sscanf(str,"%[^1-9]%d%s",tmp1,&digit,tmp2);
	*/
	
	/*2.读取指定长度的字符串*/
	char str1[] = {"123abc45"};
	sscanf(str1,"%6s",tmp1); //读取6个字符到tmp1中
	
	/*3.读取到某个字符时停止读取*/
	char str2[] = {"abcdefg"}; 
	sscanf(str2,"%[^d]",tmp1);//读取到d结束读取, 不包含d
	
	/*4.读取到指定字符集时停止读取*/
	char str3[] = {"abcdBCDE"};
	sscanf(str3,"%[^A-Z]",tmp1); //读取到A到Z之间的任一字符时停止读取

	/*5.读取仅包含指定字符集的字符串*/
	char str4[] = {"12ab78cdABfffEFG"};
	sscanf(str4,"%[0-9,a-z]",tmp1);//读取包含0-9和a-z的字符串,当读取到第一个不在这个符合的字符时结束。tmp1="12ab78cd"
	sscanf(str4,"%[0-9]%[a-z]%[A-Z]",tmp1,tmp2,tmp3); //tmp1=12,tmp2=ab,tmp3为空,因为读到7时不是[A-Z]所以结束
	cout << tmp1 <<"-" <<tmp2<<"-"<< tmp3 << endl;

	/*6.跳过某个数据不读取*/
	char str6[] = {"hello world"};
	sscanf(str6,"%*s%s",tmp1); //星号*表示跳过此数据不读取,过滤掉hello.tmp1=world

	/*7.获取指定区间的字符串*/
	char str5[] = {"iios/12DDWDFF@122"}; //获取/与@之间的字符串
	sscanf(str5,"%*[^/]/%[^@]",tmp1);//先读取到/,然后把读取到的这些数据忽略,又忽略/直到遇到@,不含@

	/*8.在一个字符串中跳过某些字符*/
	char str7[] = {"iosVSandrooid"};
	sscanf(str7,"%[a-z]VS%[a-z]",tmp1,tmp2); //跳过VS不读取

	/*9.读取以某些字符隔开的字符串*/
	char str8[] = {"android|ios|wp7"}; //读取以|隔开的字符串
	//sscanf(str8,"%[^|]|%[^|]|%[^|]",tmp1,tmp2,tmp3); //最后一个%[^|]因为后面再没有|,读取到字符串尾后会自然结束 
	sscanf(str8,"%[^|]|%[^|]|%s",tmp1,tmp2,tmp3); //先读取到|,忽略|再读取到下一个|

	/*10.提取邮箱地址*/
	char str9[] = {"email:beging@gmail.com"};
	sscanf(str9,"%[^:]:%[^@]@%s",tmp1,tmp2,tmp3); //%s前的@是忽略不读取
	cout << tmp1 <<","<<tmp2<<","<<tmp3<<endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值