sscanf()的用法

sscanf的作用:从一个字符串中读进于指定格式相符的数据。利用它可以从字符串中取出整数、浮点数和字符串。

sscanf和scanf的区别:scanf是以键盘作为输入源,sscanf是以字符串作为输入源(即处理已经输入的字符串)

原型:

int sscanf(const char * str, const char * format, 用来接收的参数);

说明:

sscanf()会将参数str的字符串根据参数format字符串来转换格式并格式化数据。转换后的结果存于对应的参数内。成功则返回参数数目,失败则返回0

例如:

1. 取指定长度的字符串

#include<stdio.h>
#include<string.h>
int main()
{
    char str[100];
    sscanf("12345","%4s",str);
    printf("%s\n",str);
    return 0;
}

//结果1234

 

2. 读入字符串

#include<stdio.h>
#include<string.h>
int main()
{
     char str1[100], str2[100], str3[100];
      gets(str1);
      sscanf(str1,"%s%s",str2,str3);
      printf("%s %s\n",str2,str3);
    return 0;
}

 

3.%*d和%*s加了(*)表示跳过此数据不读入(也就是不把此数据读入参数中)

#include<stdio.h>
#include<string.h>
int main()
{
    char str[100];
    sscanf("1234abcd","%*d%s",str);
    printf("%s\n",str);
    return 0;
}

//结果abcd

4.  ^取到指定字符为止的字符串(类似正则表达式,但不完全一样!!!)

#include<stdio.h>
#include<string.h>
int main()
{
    char str[100];
    sscanf("1234+abc","%[^+]",str);
    printf("%s\n",str);
    return 0;
}

//结果1234

 

5.取到指定字符集为止的字符串。如遇到小写字母为止的字符串

#include<stdio.h>
#include<string.h>
int main()
{
    char str[100];
    sscanf("1234+abc1234","%[^a-z]",str);
    printf("%s\n",str);
    return 0;
}

//输出1234+

 

取仅包含数字和小写字母的字符串

#include<stdio.h>
#include<string.h>
int main()
{
    char str[100];
    sscanf("123456abcdefBFRGTY7890","%[1-9a-z]",str);
    printf("%s\n",str);
    return 0;
}
//输出123456abcdef

 

posted @ 2020-05-06 19:01  何梦吉他  阅读(2461)  评论(0编辑  收藏  举报