函式
<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

另見