函数
<cstdio>

snprintf

int snprintf ( char * s, size_t n, const char * format, ... );
向带大小的缓冲区写入格式化输出
Compose a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by s (taking n as the maximum buffer capacity to fill).

If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function.

A terminating null character is automatically appended after the content written.

format 参数之后,函数期望至少有 format 所需的那么多额外参数。

参数

s
指向存储结果 C 字符串的缓冲区的指针。
The buffer should have a size of at least n characters.
n
Maximum number of bytes to be used in the buffer.
生成的字符串长度最多为n-1, leaving space for the additional terminating null character.
size_t 是一个无符号整数类型。
format
一个 C 字符串,包含一个格式化字符串,其遵循与 printf 中的 format 相同的规范(详见 printf)。
... (附加参数)
根据格式字符串,函数可能需要一系列附加参数,每个参数包含一个用于替换格式字符串中格式说明符的值(或者,对于n).
,是指向存储位置的指针)。这些参数的数量应至少与格式说明符中指定的值的数量一样多。额外的参数会被函数忽略。

返回值

The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character.
If an encoding error occurs, a negative number is returned.
Notice that only when this returned value is non-negative and less than n, the string has been completely written.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* snprintf example */
#include <stdio.h>

int main ()
{
  char buffer [100];
  int cx;

  cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );

  if (cx>=0 && cx<100)      // check returned value

    snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );

  puts (buffer);

  return 0;
}

输出
The half of 60 is 30, and the half of that is 15.


有关格式化的更多示例,请参阅 printf

另见