sscanf函数用法详解

2024-10-15 17:53:55

1、sscanf函数原型为: int sscanf(const char *buffer , const char *format , [argument ]...);参数说明: buffer 为存储的数据 format 为格式控制字符串 argument 选择性设定字符串函数功能: 从一个字符串中读进与指定格式相符的数据的函数,即sscanf会从buffer里读取数据,依照format的格式将数据写入到argument里

sscanf函数用法详解

2、sscanf函数举例 1:# inclu蟠校盯昂de <stdio.h>int main(void){ char str[512]; //此处buf是数组名,它的意思是将hello 123456以%s的形式存入str中?? sscanf("hello 123456", "%s", str); printf("%s\n", str); system("pause"); return 0;}在这个例子中,sscanf只将字符串“hello”赋给了变量str,说明sscanf使用格式“%s”赋值遇到空格则会结束。

sscanf函数用法详解

3、sscanf函数举例2:# include <stdio.h>int main(void){ char str[512]; sscanf("helloworld!", "%4s", str); printf("%s\n", str); system("pause"); return 0;}这个例子演示了使用sscanf取指定长度的字符串。这里取最大长度为4字节的字符串,即输出“hell”

sscanf函数用法详解

4、sscanf函数举例3:# include <stdio.h>int main(void){ char str[512]; sscanf("123456abcdedf", "%[^a-z]",str); printf("%s\n",str); system("pause"); return 0;}这里演示sscanf函数取到指定字符为止的字符串。这个例子中取遇到任意小写字母为止的字符串,所以结果为“123456”。

sscanf函数用法详解

5、sscanf函数举例4:# include <stdio.h>int main(void){ c茑霁酌绡har str[512]; char str1[512]; sscanf("123456abcdedfBCDEF", "%[1-9a-z]", str); printf("%s\n", str); sscanf("123456abcdedfBCDEF", "%[1-9A-Z]", str1); printf("%s\n", str1); system("pause"); return 0;}这个例子演示sscanf函数取仅包含指定字符集的字符串。第一个sscanf函数取仅包含1到9和小写字母的字符串,输出结果为“123456abcdedf”第二个sscanf函数取不到1-9和A-Z的任何字符就会停止,所以输出“123456”,而不是“123456BCDEF”

sscanf函数用法详解

6、sscanf函数举例5:# include <stdio.h>int main(void){ int a, b, c, d; sscanf("192.168.1.1", "%d.%d.%d.%d",&a,&b,&c,&d); printf("%d\n%d\n%d\n%d\n", a,b,c,d); system("pause"); return 0;}这个例子演示如何使用sscanf将字符串IP地址转换成整数。这里分别输出了四个整数,192、168、1、1。

sscanf函数用法详解

7、sscanf函数举例6:# include <stdio.h>int main(void){ c茑霁酌绡har str[512]; sscanf("hello/you are good!@world", "%*[^/]/%[^@]", str); printf("%s\n", str); system("pause"); return 0;}这个例子比较复杂,我们指定赋值格式为"%*[^/]/%[^@]",其中“*”表示跳过此数据,不进行读取。“%*[^/]”则表示跳过字符“/”前面所有的数据,“/%[^@]”则表示,读取“/”后面的所有数据,知道碰到字符“@”,所以这个例子输出结果为“you are good!”

sscanf函数用法详解
猜你喜欢