您的位置:首页 > 其它

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

2017-09-03 14:42 274 查看
假如有 eng_1_2_3.jpg 的字符串,我们想取出其中的 1_2_3.jpg 子串,可以使用sscanf来实现。

我们使用如下测试数据进行测试:



测试代码如下:

char szbuf[MAX_PATH] = {0},szbuf1[MAX_PATH] = {0},szbuf2[MAX_PATH] = {0};

FILE* fp = fopen("1.txt", "rt");

if (fp)
{
while (fgets(szbuf,MAX_PATH,fp) != NULL)
{
sscanf(szbuf,"%[^_]_%s",szbuf1,szbuf2);
cout<<"szbuf1 = "<<szbuf1<<" , szbuf2 = "<<szbuf2<<endl;
}

fclose(fp);

fp = NULL;
}
else
{
cout<<"打开文件失败!"<<endl;
}

测试结果:



下面附上 sscanf 函数其它使用的一些实例:

[cpp] view
plain copy

#include<stdio.h>  

#include<stdlib.h>  

#include<string.h>  

  

int main(){  

    char str[100];  

    //用法一:取指定长度的字符串  

    sscanf("12345","%4s",str);  

    printf("用法一\nstr = %s\n",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("用法二\ntime = %d-%d-%d %d:%d:%d\n",year,month,day,hour,minute,second);  

  

    //用法三:读入字符串  

    sscanf("12345","%s",str);  

    printf("用法三\nstr = %s\n",str);  

  

    //用法四:%*d 和 %*s 加了星号 (*) 表示跳过此数据不读入. (也就是不把此数据读入参数中)  

    sscanf("12345acc","%*d%s",str);  

    printf("用法四\nstr = %s\n",str);  

  

    //用法五:取到指定字符为止的字符串。如在下例中,取遇到'+'为止字符串。  

    sscanf("12345+acc","%[^+]",str);  

    printf("用法五\nstr = %s\n",str);  

  

    //用法六:取到指定字符集为止的字符串。如在下例中,取遇到小写字母为止的字符串。  

    sscanf("12345+acc121","%[^a-z]",str);  

    printf("用法六\nstr = %s\n",str);  

    return 0;  

}  



sscsnf函数的详细的使用说明可以查阅MSDN。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐