C++ snprintf函数

printf()/sprintf()/snprintf()区别 
先贴上其函数原型
printf( const char *format, ...)    格式化输出字符串,默认输出到终端-----stdout
sprintf(char *dest, const char *format,...)     格式化输出字符串到指定的缓冲区

snprintf(char *dest, size_t size,const char *format,...)    格式化输出字符串输出到指定的缓冲区,共size-1个字符+一个空字符‘\0’

dest: Pointer to a buffer where the resulting C-string is stored. The buffer should have a size of at least n characters.

size:Maximum number of bytes to be used in the buffer. The generated string has a length of at most n-1, leaving space for the additional terminating null character. size_t is an unsigned integral type.

注意点:
1   sprintf是一个不安全函数,src串的长度应该小于dest缓冲区的大小,(如果src串的长度大于或等于dest缓冲区的大小,将会出现内存溢出。)
2   snprintf中源串长度应该小于目标dest缓冲区的大小,且size等于目标dest缓冲区的大小。(如果源串长度大于或等于目标dest缓冲区的大小,且size等于目标dest缓冲区的大小,则只会拷贝目标dest缓冲区的大小减1个字符,后加'\0';该情况下,如果size大于目标dest缓冲区的大小则溢出。)
3   snprintf ()函数返回值问题,   如果输出因为size的限制而被截断,返回值将是“如果有足够空间存储,所能输出的字符数(不包括字符串结尾的'\0')”,这个值和size相等或者比size大!也就是说,如果可以写入的字符串是"0123456789ABCDEF"共16位,但是size限制了是10,这样 snprintf() 的返回值将会是16 而不是10

你可能感兴趣的:(C++ snprintf函数)