描述
sscanf通常被用来解析并转换字符串,其格式定义灵活多变,可以实现很强大的字符串解析功能。
sscanf的原型
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5488fcfa6041e8113f46f4e3d6d875e7.png)
编写小练习
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void func01()
{
char msg[1024] = "phone:1234567;2024/5/20;崔款了";
long long phone = 0;
int year = 0;
int month = 0;
int day = 0;
char content[64] = "";
int num = sscanf(msg, "phone:%lld;%d/%d/%d;%s", &phone, &year, &month, &day, content);
printf("%lld\n",phone);
printf("%d\n", year);
printf("%d\n", month);
printf("%d\n", day);
printf("%s\n", content);
printf("成功转换个数:%d\n", num);
}
void func02()
{
char str[1024] = "12345abcde";
char buf[1024] = {0};
sscanf(str, "%*d%s",buf);
printf("buf:%s\n",buf);
}
void func03()
{
char buf[1024] = { 0 };
char str[1024] = "abcde12345";
sscanf(str, "%*[a-z]%s", buf);
printf("buf:%s\n", buf);
}
void func04()
{
char str[1024] = "12345abcde";
char buf[1024] = { 0 };
sscanf(str, "%5s", buf);
printf("buf:%s\n", buf);
}
void func05()
{
char str[1024] = "12345abcde";
char buf[1024] = { 0 };
sscanf(str, "%*d%[a-z]", buf);
printf("buf:%s\n", buf);
}
void func06()
{
char str[1024] = "aaBbcCde";
char buf[1024] = { 0 };
sscanf(str, "%[abc]", buf);
printf("buf:%s\n", buf);
}
void func07()
{
char str[1024] = "aaBbcCde12345";
char buf[1024] = { 0 };
sscanf(str, "%[^b]", buf);
printf("buf:%s\n", buf);
}
void func08()
{
char str[128] = "abcde#wutao@12345";
char buf[128] = "";
sscanf(str, "%*[^#]#%[^@]",buf);
printf("buf:%s\n",buf);
}
int main()
{
func08();
return 0;
system("pause");
}