C stdio snprintf() 函式
示例
將格式化的字串寫入 char
陣列
char destination[50];
snprintf(destination, 50, "Hello %s!", "World");
printf("%s", destination);
自己動手試一試 »
定義和用法
snprintf()
函式將格式化的字串後跟一個 \0
空終止字元寫入 char
陣列。
snprintf()
函式定義在 <stdio.h>
標頭檔案中。
format 字串可以包含 **格式說明符**,這些說明符描述瞭如何表示傳遞給函式的其他引數。有關格式說明符的詳細資訊,請參閱 printf() 參考頁。
語法
snprintf(char * destination, size_t * size, const char * format, arg1, arg2...);
引數值
引數 | 描述 |
---|---|
destination | 必需。一個 char 陣列,格式化後的字串將被寫入其中。 |
大小 | 必需。指定 *destination* 陣列的大小。此函式最多將字元寫入該陣列,包括空終止字元。 |
format | 必需。一個字串,表示要寫入陣列的資料格式。 |
arg1, arg2... | 可選。任意數量的附加引數,可以使用 *format* 引數中的說明符將它們的值格式化並寫入 *destination* 陣列。 |
技術詳情
返回 | 一個 int 值,表示打算寫入陣列的字元數(不包括空終止字元)。如果此值大於或等於 *size* 引數,則某些字元無法寫入陣列。如果發生錯誤,則返回一個負數。 |
---|