C stdio sprintf() 函式
示例
將格式化字串寫入 char
陣列
char destination[50];
sprintf(destination, "Hello %s!", "World");
printf("%s", destination);
自己動手試一試 »
定義和用法
sprintf()
函式將格式化字串(後跟 \0
空終止字元)寫入 char
陣列。
sprintf()
函式定義在 <stdio.h>
標頭檔案中。
“格式”字串可以包含 **格式說明符**,它們描述瞭如何表示傳遞給函式的其他引數以及在何處表示它們。有關格式說明符的詳細資訊可以在 printf() 參考頁面上找到。
注意:此函式不考慮陣列的大小。如果寫入過多字元,它可能會開始覆蓋屬於其他變數或其他程式的記憶體。此函式的安全替代方案是 snprintf()
函式。
語法
sprintf(char * destination, const char * format, arg1, arg2...);
引數值
引數 | 描述 |
---|---|
destination | 必需。一個 char 陣列,格式化字串將寫入其中。 |
format | 必需。一個字串,表示要寫入陣列的資料的格式。 |
arg1, arg2... | 可選。任意數量的附加引數,它們的值可以使用 *format* 引數中的說明符進行格式化並寫入 *destination* 陣列。 |
技術詳情
返回 | 一個 int 值,表示寫入陣列的字元數(不包括空終止字元)。如果發生錯誤,則返回一個負數。 |
---|