C language learning: snprintf () function

Prototype:

int snprintf(char* dest_str,size_t size,const char* format,...);

Function:

  • First variable parameters " ..." according to formatthe format as formatted string, and then copy it to dest_strthe.

head File:

#include<stdio.h>

Precautions:

  • If the string length after formatting 小于size, the string copied to all dest_strof then 'at the end of the string \0';

  • If the string length after formatting 大于或等于size, the string is (size-1)copied to dest_strthen add at the end of the string ' \0'.

  • Function return value is the length of the format string.

Example of use:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void){
 
	char dest_str[4096];
	memset(dest_str,0,sizeof(dest_str));
 
	char *s1 = "Linux程序设计";
	int size = strlen(s1);
	int year = 2014;
	int month = 11;
	int day = 6;
 
	snprintf(dest_str,sizeof(dest_str),"字符串:%s\n长度是:%d\n今天是:%d年%d月%d日\n",s1,size,year,month,day);
 
	printf("%s",dest_str);
 
	return 0;
}

Results of the:

字符串:Linux程序设计
长度是:17
今天是:2019年9月24日
Published 100 original articles · won praise 45 · views 640 000 +

Guess you like

Origin blog.csdn.net/wangzhongshun/article/details/101271017