zoukankan      html  css  js  c++  java
  • 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
    ",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
    ",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
    ",str);
        return 0;
    }

    //结果abcd

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

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

    //结果1234

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

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

    //输出1234+

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

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char str[100];
        sscanf("123456abcdefBFRGTY7890","%[1-9a-z]",str);
        printf("%s
    ",str);
        return 0;
    }
    //输出123456abcdef
  • 相关阅读:
    POJ 1811 Prime Test (Rabin-Miller强伪素数测试 和Pollard-rho 因数分解)
    POJ 1200 Crazy Search (哈希)
    POJ 1061 青蛙的约会 (扩展欧几里得算法)
    POJ 1035 Spell checker (模拟)
    hud 2554 N对数的排列问题 (规律)
    HDU 2522 A simple problem (模拟)
    Python环境配置及项目建立
    IDEA通过MyBatis generator生成数据库表的对象
    复制、粘贴、剪切 操作
    下载歌曲(以QQ音乐为例)
  • 原文地址:https://www.cnblogs.com/hemengjita/p/12838258.html
Copyright © 2011-2022 走看看