sprintf 与 snprintf(_snprintf)的区别(n的含义)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
*sprintf 与 snprintf的区别
*/

void main(){
	int a, b;
	int i = 10;
	char c1[100];
	char c2[100];

	//将字符数组格式化,返回格式化完成后数组大小,不管数组大小
	a = sprintf(c1, "result is %d", i);
	printf("%s %d\n", c1, a);

	//VC6.0里面是_snprintf,但在有的编译器里面没有下划线
	//必须要指定指定数组的容量,一旦越界就返回-1,否则返回字符数量
	//传的值是数组容量,必须比字符数量大1以上,如传13,返回12;如果传12就会出错,并返回-1;
	b = _snprintf(c2, 13, "result is %d", i);
	printf("%s %d\n", c2, b);

	//与一些字符数组操作函数类似,带n的函数需要指定大小
	strcpy(c1,"hello");
	puts(c1);

	//参数值要大于字符串长度,5个字符的话至少需要传入6,才会连‘\0’也拷贝
	//否则只能拷贝指定个数的字符
	strncpy(c2, "world", 6);
	puts(c2);
}
 


sprintf 与 snprintf(_snprintf)的区别(n的含义)

 

你可能感兴趣的:(printf)