C语言 sscanf函数补充

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/* sscanf特殊用法补充 */

void test()
{
    const char * p1 = "333<key:value>abcde";
    const char * p2 = "<key:value>abcde";
    int rc = 0;
    char buf1[1024] = { 0 };
    char buf2[1024] = { 0 };
    char buf3[1024] = { 0 };
    int index = 0;

    /*
    目标:
        提取<>中的内容
    */

    rc = sscanf(p1, "%[^<]<%[^>]>%n%s", buf1, buf2, &index, buf3);
    printf("==11111==rc[%d]==buf1[%s]===buf2[%s]=buf3[%s]===index[%d]=====\n", rc, buf1, buf2, buf3, index);
    /*
    说明:
        %n获取的是截止到>这个数据的长度,这个长度是相对于源字符串p1,而不是相对于%[^<],%n可以放在任何地方,他就是用来统计到当前位置的长度

        特别强调,%n不包括在返回值中,这里rc的值是3,而不是4
    */

    //注意点
    memset(buf1, 0, 1024);
    memset(buf2, 0, 1024);
    memset(buf3, 0, 1024);
    index = 0;
    rc = sscanf(p2, "%[^<]<%[^>]>%n%s", buf1, buf2, &index, buf3);
    printf("====2222222==rc[%d]==buf1[%s]===buf2[%s]=buf3[%s]===index[%d]=====\n", rc, buf1, buf2, buf3, index);
    /*
    强调:
        当匹配p2时,什么都没有匹配到,原因是p2不符合%[^<]这个条件,p2以<开始,所以%[^<]匹配不到任何东西,需要注意这一点
        强调sscanf匹配时,必须能匹配到数据,数据不可以不存在,这一点和正则不同
    */

}

int main(int argc, char *argv[])
{
    test();
    printf("-----ok------\n");
    getchar();
    return 0;
}

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//sscanf指定检索长度

void test()
{
    const char* p = "%8888asdas";
    char buf[32] = { 0 };
    int n = 0;

    if (sscanf(p, "%%%x", &n))
    {
        printf("---111---[%d]------\n", n);    //打印‭559242‬,因为提取的十六进制数是8888a
    }

    if (sscanf(p, "%%%2x", &n))
    {
        printf("----22--[%d]------\n", n);    //打印‭136,因为提取的十六进制数是88
    }

    //说明: 其他提取方式类同,例如 %3s   表示提取3个字符
}

int main()
{
    test();
    return 0;
}

 

posted on 2019-07-31 21:51  寒魔影  阅读(340)  评论(0)    收藏  举报

导航