天天看点

sprintf_s() 、sprintf()和printf()区别和用法

int sprintf_s(char *buffer,size_t sizeOfBuffer,const char *format [,argument] …);

eg:

char buff[256];
    sprintf_s(buff,, "../cfg/%d_%d.png", i, j);
           

异同

  • printf函数把结果输出。
  • sprintf函数把结果输出到指定的字符串中。
  • sprintf_s()是sprintf()的安全版本,通过指定缓冲区长度来避免sprintf()存在的溢出风险
  • sprintf_s 会检查格式化字符的合法性,而sprintf只会检查其是否是空指针

需要包含的头文件

stdio.h

eg

将”test 1 2”写入数组s中

#include<stdio.h>
int main(int argc, char *avgv[])
{
    char s[];
    sprintf(s,"%s%d%c","test",,'2');
    //第一个参数就是指向要写入的那个字符串的指针,剩下的就和printf()一样

    printf("%s%d%c","test",,'2');
    //对保存后的字符串输出
    printf("%s",s);
    return ;
}
           

ref

https://blog.csdn.net/tigernana/article/details/6916491

https://blog.csdn.net/lijie0073237/article/details/13767519

https://blog.csdn.net/zyazky/article/details/52180458

继续阅读