sscanf

在做一道九度上机题时,突然发现sscanf()函数非常有用,就顺便从网上搜集资料整理一下。

       sscanf() 的作用:从一个字符串中读进与指定格式相符的数据.

原型: int sscanf (const char *str,const char * format,........);

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

注意:sscanf与scanf类似,都是用于输入的,只是后者以键盘(stdin)为输入源,前者以固定字符串为输入源。

例子:

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

int main(){
    char str[100];
    //用法一:取指定长度的字符串
    sscanf("12345","%4s",str);
    printf("用法一
str = %s
",str);

    //用法二:格式化时间
    int year,month,day,hour,minute,second;
    sscanf("2013/02/13 14:55:34","%d/%d/%d %d:%d:%d",&year,&month,&day,&hour,&minute,&second);
    printf("用法二
time = %d-%d-%d %d:%d:%d
",year,month,day,hour,minute,second);

    //用法三:读入字符串
    sscanf("12345","%s",str);
    printf("用法三
str = %s
",str);

    //用法四:%*d 和 %*s 加了星号 (*) 表示跳过此数据不读入. (也就是不把此数据读入参数中)
    sscanf("12345acc","%*d%s",str);
    printf("用法四
str = %s
",str);

    //用法五:取到指定字符为止的字符串。如在下例中,取遇到'+'为止字符串。
    sscanf("12345+acc","%[^+]",str);
    printf("用法五
str = %s
",str);

    //用法六:取到指定字符集为止的字符串。如在下例中,取遇到小写字母为止的字符串。
    sscanf("12345+acc121","%[^a-z]",str);
    printf("用法六
str = %s
",str);
    return 0;
}

原文地址:https://www.cnblogs.com/ljhacm/p/6753689.html