///
/// @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;
}
sscanf的用法
最新推荐文章于 2023-04-11 23:37:34 发布