今天看内核链表的代码,其中有句:
<span style="font-size:14px;">for(i=0;i<5;i++)
{
sprintf(pstudent[i].name,"student%d",i+1)
.........
}</span>
刚开始没仔细看,以为就是普通的打印,但后面的代码发现,需要给pstudent[i].name赋值,才知这句的含义。
sprintf与printf都是打印,的区别是:sprintf是打印到字符串中,printf是打印到命令行上。
sprintf函数原型为:
int sprintf( char *buffer, const char *format, [ argument] … );
第三个参数可有可无,根据需要。
用法实例如下:
sprintf(s,"%d",123);作用:把整数123打印成字符串保存在s中。
上例中,循环的结果为:
pstudent[0].name=student1,
pstudent[1].name=student2,
pstudent[2].name=student3,
pstudent[3].name=student4,pstudent[4].name=student5,
它与strcpy的作用差不多,但是比strcpy功能更强大一些,像上例的循环,如果用strcpy实现,只能用5个语句,分别赋值,不能采取循环的方式。因为strcpy(pstudent[i],"student"),第二个参数只能是固定的字符串,不能使%d。