C库中的snprintf()

函数的作用是:在数组缓冲区中格式化并存储一系列字符和值。snprintf()函数,其中添加了n参数,该参数指示要写入缓冲区的最大字符数(包括null字符末尾的字符数)。定义见 头文件。

null

snprintf()函数用于将printf()函数的输出重定向到缓冲区。

snprintf()还返回写入缓冲区的字符数(不包括空终止符),类似于printf语句,它返回在stdout中打印的字符数。

语法:

int snprintf(char *str, size_t size, const char *format, ...);*str : is a buffer.size : is the maximum number of bytes(characters) that will be written to the buffer.format : C string that contains a formatstring that follows the same specifications as format in printf... : the optional ( …) arguments are just the string formats like (“%d”, myint) as seen in printf.

C

// C program to demonstrate snprintf()
#include <stdio.h>
int main()
{
char buffer[50];
char * s = "geeksforgeeks" ;
// Counting the character and storing
// in buffer using snprintf
int j = snprintf(buffer, 6, "%s" , s);
// Print the string stored in buffer and
// character count
printf ( "string:%scharacter count = %d" ,
buffer, j);
// join two or more strings
char *str1 = "quick" ;
char *str2 = "brown" ;
char *str3 = "lazy" ;
int max_len = sizeof buffer;
j = snprintf (buffer, max_len, "The %s %s fox jumped over the %s dog." , str1, str2, str3);
printf ( "The number of bytes printed to 'buffer' (excluding the null terminator) is %d" , j);
if (j >= max_len)
fputs ( "Buffer length exceeded; string truncated" , stderr);
puts ( "Joined string:" );
puts (buffer);
return 0;
}


输出

string:geekscharacter count = 14The number of bytes printed to 'buffer' (including the null terminator) is 45Joined string:The quick brown fox jumped over the lazy dog.

输出:

string:geekscharacter count = 14

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享