一、sscanf 与 sprintf
(1)sscanf与scanf类似,都是用于输入的,只是scanf以屏幕(stdin)为输入源,sscanf以固定字符串为输入源。
sscanf常以空格来界定字符串,当然还有一些其他的也可以,如 : - 等
举列:
①常见用法。
char buf[10];
sscanf("123456 ", "%s", buf);
printf("%s\n", buf);
结果为:123456
②取指定长度的字符串。
sscanf("123456 ", "%4s", buf);
printf("%s\n", buf);
结果为:1234
③给定一个字符串““hello, world”,仅保留world。(注意:“,”之后有一空格)
sscanf(“hello, world”, "%*s%s", buf);
printf("%s\n", buf);
结果为:world
注意:%*s表示第一个匹配到的%s被过滤掉,即hello被过滤了
④ int a, b, c;
sscanf("2006:03:18", "%d:%d:%d", a, b, c);
(2)同理,sprintf是输出到字符串,而printf是输出到屏幕(stdout)
char str[100] = "boy";
char str2[100]={0};
sprintf(str2,"qiuoooooo is a %s,has %d",str,strlen(str));
printf("str2 = %s\n",str2);
结果为:str2 = qiuoooooo if a boy, has 3
二、snprintf //其实sprintf和snprintf的区别就相当 strcmp 和 strncmp
int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n 的话,将不会溢出。
函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。
example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10]={0,};
snprintf(str, sizeof(str), "0123456789012345678");
printf("str=%s/n", str);
return 0;
}
结果为:str=012345678