今天偶遇到一个关于关于此函数的一个问题,好像是一个大学考试题,sprintf()函数是向buf缓存区输出一定格式的字符串,例如:
#include<stdio.h>int main(){ char buf[1024]={0}; char *p = "hello"; int n = sprintf(buf,"%s",p); printf("str: %sn",buf); printf("cont : %dn",n);} 输出str : hellocont : 5上面的例子是把p指针所指向的内容以“%s”格式输入到buf里面,此函数的返回值是实习向buf中写入的字符数,所以可以利用此特点进行字符串拼接,如下例
#include<stdio.h>int main(){ int i=0; int j=0; char *str[3]={"hello ","word ","!! "}; char buf[1024]={0}; for(i=0;i<3;i++) { j += sprintf(buf+j,"%s",str[i]); } printf("%sn",buf);//(输出结果:hello word !! )}这里解释一下j += sprintf(buf+j,"%s",str[i]);,在sprintf函数的第一个参数+j代表字符串从buf的哪个位置开始向buf里面输入,而不覆盖掉之前的字符,在这里不建议这样使用字符串拼接,建议使用标准函数strncat();