sscanf()定义于头文件stdio.h。sscanf()会将参数str的字符串根据参数format字符串来转换并格式化数据。格式转换形式请参考scanf()。转换后的结果存于对应的参数内。
一些代码演示:
#include
int main()
{
char result_char[100];
//int result_int;
sscanf("helloworld","%s",result_char);
printf("the result is : %s", result_char);
return 0;
}
运行:
sscanf遇到 空格 就会返回 (\n 也同样会返回 \n 之前的字符)
其余的符号并不会返回(我只验证常用的,不包括所有)
#include
int main()
{
char result_char[100];
//int result_int;
sscanf("hello world","%s",result_char);
printf("the result is : %s", result_char);
return 0;
}
#include
int main()
{
char result_char[100];
int result_int;
float result_float;
sscanf("helloworld 2023 12.12","%s %d %f",result_char, &result_int, &result_float);
printf("the result is : %s, time: %d, data: %f\n", result_char, result_int, result_float);
return 0;
}
#include
int main()
{
char result_char[100];
int result_int;
float result_float;
//sscanf("helloworld-1212 2023 12.12","%s %d %f",result_char, &result_int, &result_float);
//the result is : helloworld-1212, time: 2023, data: 12.120000
sscanf("helloworld:1212 2023 12.12","%s %d %f",result_char, &result_int, &result_float);
//the result is : helloworld:1212, time: 2023, data: 12.120000
sscanf("helloworld1212 2023 12.12","%s %d %f",result_char, &result_int, &result_float);
//the result is : helloworld1212, time: 2023, data: 12.120000
printf("the result is : %s, time: %d, data: %f\n", result_char, result_int, result_float);
return 0;
}
#include
int main()
{
char result_char[100];
int result_int;
float result_float;
// 等号两边最好不要加 空格,不同类型用 分号 分开
// 这里默认都是接收 = 后面的东西
// "%*[^=] = %[^;]; time=%d; data=%f" 这里也用分号分开
sscanf("name=helloworld; time=2023; data=12.12","%*[^=] = %[^;]; time=%d; data=%f",result_char, &result_int, &result_float);
printf("the result is :%s, time:%d, data:%f\n", result_char, result_int, result_float);
return 0;
}
#include
int main()
{
char result_char[100];
//int result_int;
//float result_float;
// [a-z0-5] 字符指定为a-z的 数字指定为 0-5的
sscanf("hello2023world6789","%[a-z0-5]",result_char);
// 不会打印 6-9的数字
printf("the result is :%s\n", result_char);
return 0;
}
#include
int main()
{
char result_char[100];
//int result_int;
//float result_float;
// 不要 o-z的字符
sscanf("helloworld","%[^o-z]",result_char);
printf("the result is :%s\n", result_char);
return 0;
}
还有很多用法大家可以去百度下,这里只是做一些简单的总结。